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 useful.
Basically if any thing goes wrong I want to stop and print out what went wrong.
Can anyone give me any pointers?
A successful ping on your local network can be trapped using
ERRORLEVEL
.Its extremely easy! Create a file that contains:
So now when you start it, it will launch your program as normal. But when anything goes wrong it exits and continues the script inside the first file. Now there you can put your own commands in.
I guess this feature was added since the OP but for future reference errors that would output in the command window can be redirected to a file independent of the standard output
command 1> file - Write the standard output of command to file
command 2> file - Write the standard error of command to file
Python Unittest, Bat process Error Codes:
Bat codes:
Other than ERRORLEVEL, batch files have no error handling. You'd want to look at a more powerful scripting language. I've been moving code to PowerShell.
The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.
Right now, it looks like any time invested in learning and using PowerShell will be time well spent.
I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.
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.
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.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.