Batch Files - Error Handling

后端 未结 7 1680
谎友^
谎友^ 2020-11-28 08:54

I\'m currently writing my first batch file for deploying an asp.net solution. I\'ve been Googling a bit for a general error handling approach and can\'t find anything really

7条回答
  •  执笔经年
    2020-11-28 09:36

    I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.

    yourCommand && (
      echo yourCommand was successful
    ) || (
      echo yourCommand failed
    )
    

    There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.

    yourCommand && (
      someCommandThatMayFail
    ) || (
      echo This will fire if yourCommand or someCommandThatMayFail raises an error
    )
    

    The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call ), which does nothing except set the ERRORLEVEL to 0. There is a corollary (call) that does nothing except set the ERRORLEVEL to 1.

    yourCommand && (
      someCommandThatMayFail
      (call )
    ) || (
      echo This can only fire if yourCommand raises an error
    )
    

    See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.

提交回复
热议问题