gpt4 book ai didi

android - 无法捕获Exec类型的Gradle任务的异常

转载 作者:行者123 更新时间:2023-12-03 03:55:18 25 4
gpt4 key购买 nike

我创建了gradle任务来检查是否安装了程序,它可以正常工作,但是我发现在我执行的命令不存在的环境中,它可能引发异常。我试图捕捉引发但没有运气的异常。如果由于命令不存在导致我的任务失败,我该如何优雅地处理异常并继续构建过程?

错误:

失败:生成失败,发生异常。

  • 出了什么问题:
    任务':isGitLFSInstalled'的执行失败。

    A problem occurred starting process 'command 'command''


  • 代码:
    task isGitLFSInstalled(type: Exec) {
    commandLine 'command', '-v', 'git-lfs' // Fails here on environments that dont have "command"
    ignoreExitValue true
    standardOutput = new ByteArrayOutputStream()

    ext.output = {
    return standardOutput.toString()
    }

    doLast {
    if (execResult.exitValue != 0) {
    throw new GradleException("Git LFS is not installed, please build project after installing Git LFS.\n" +
    "Refer to the following URL to setup Git LFS: https://git-lfs.github.com/")
    }
    }

    }

    最佳答案

    您面临的问题描述为here。用try / catch括住commandLine的原因并不简单:commandLine不会执行您的命令,它只是将命令设置为在Exec任务运行时执行。

    一种方法是不使用任务来执行命令。例如,您可以使用try / catch包裹在finalizedBy中的ProcessBuilder,它将仅在执行阶段运行:

    task myTask {
    finalizedBy {
    try {
    def proc = new ProcessBuilder("command", "-v", "git-lfs")
    proc.start().waitFor()
    // Do something with stdout or whatever.
    } catch (Exception e) {
    println("Couldn't find git-lfs.")
    }
    }
    }

    我现在没有很多时间,但我希望能有所帮助。

    关于android - 无法捕获Exec类型的Gradle任务的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60937840/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com