Обработчик ошибок cmd

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?

John Saunders's user avatar

John Saunders

160k26 gold badges247 silver badges397 bronze badges

asked Jul 22, 2009 at 9:15

handles's user avatar

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.

Community's user avatar

answered Jun 13, 2013 at 11:27

dbenham's user avatar

dbenhamdbenham

127k28 gold badges249 silver badges385 bronze badges

7

Using ERRORLEVEL when it’s available is the easiest option. However, if you’re calling an external program to perform some task, and it doesn’t return proper codes, you can pipe the output to ‘find’ and check the errorlevel from that.

c:mypathmyexe.exe | find "ERROR" >nul2>nul
if not ERRORLEVEL 1 (
echo. Uh oh, something bad happened
exit /b 1
)

Or to give more info about what happened

c:mypathmyexe.exe 2&1> myexe.log
find "Invalid File" "myexe.log" >nul2>nul && echo.Invalid File error in Myexe.exe && exit /b 1
find "Error 0x12345678" "myexe.log" >nul2>nul && echo.Myexe.exe was unable to contact server x && exit /b 1

answered Aug 27, 2013 at 16:55

M Jeremy Carter's user avatar

1

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.

answered Jul 22, 2009 at 10:52

Brad Bruce's user avatar

Brad BruceBrad Bruce

7,6083 gold badges38 silver badges60 bronze badges

3

A successful ping on your local network can be trapped using ERRORLEVEL.

@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT

michaelb958--GoFundMonica's user avatar

answered Jul 9, 2013 at 13:38

Rob Davis's user avatar

Rob DavisRob Davis

611 silver badge1 bronze badge

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

answered Feb 6, 2015 at 15:36

TakenItEasy's user avatar

Python Unittest, Bat process Error Codes:

if __name__ == "__main__":
   test_suite = unittest.TestSuite()
   test_suite.addTest(RunTestCases("test_aggregationCount_001"))
   runner = unittest.TextTestRunner()
   result = runner.run(test_suite)
   # result = unittest.TextTestRunner().run(test_suite)
   if result.wasSuccessful():
       print("############### Test Successful! ###############")
       sys.exit(1)
   else:
       print("############### Test Failed! ###############")
       sys.exit()

Bat codes:

@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
  echo Error found. Waiting here...
  pause
) || (
  echo This time of test is ok.
)
)

answered Sep 24, 2017 at 7:54

Tonny's user avatar

TonnyTonny

212 bronze badges

Its extremely easy!
Create a file that contains:

call <filename>  // the file you made
cls
echo An error occured!
<Your commands>
pause

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.

answered Nov 17, 2016 at 19:51

BlazeLP's user avatar

BlazeLPBlazeLP

1351 silver badge8 bronze badges

0

Error Handling in Batch Script

Every scripting and programming language contains an error handler like Java contains try-catch for error handling. In a Batch script, there is no direct way to do this, but we can create an error handler in the Batch script using a built-in variable of the Batch script name %ERRORLEVEL%.

This article will show how we can create a Batch script to handle errors and failures. Also, we are going to some examples that make the topic easier.

Error Handling in Batch Script

When a command successfully executes, it always returns an EXIT CODE that indicates whether the command successfully executed or failed to execute. So, to create an error handling in a Batch file, we can use that EXIT CODE in our program.

You can follow below general format to create an error handler:

@Echo off
SomeCommand && (
  ECHO Message for Success
) || (
  ECHO Message for Failure or Error
)

We can also do that by checking the variable named %ERRORLEVEL%. If the variable contains a value not equal to 0, then there might be a problem or error when executing the command. To test the %ERRORLEVEL% variable, you can follow the below example codes:

@ECHO off
Some Command Here !!!
IF %ERRORLEVEL% NEQ 0 (Echo Error found when running the command &Exit /b 1)

You must note that the keyword NEQ means Not Equal. And the variable %ERRORLEVEL% will only contain a non-zero value if there is a problem or error in the code.

An Example That Contains Errors

Below, we shared an example. We will run a Batch file named Your_file.bat from a location.

We intentionally removed that file from the directory. So it’s an error command.

The code for our example will be:

@echo off
ECHO Running a Batch file
CD G:BATCH
CALL Your_file.bat
IF  errorlevel 1 GOTO ERROR
ECHO The file run successfully.
GOTO EOF

:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1

:EOF

Now, as the file doesn’t exist in the directory, it will show an error, and you will get the below output when you run the code shared above.

Output:

Running a Batch file
The system cannot find the path specified.
'Your_file.bat' is not recognized as an internal or external command,
operable program or batch file.
The file didn't run successfully.

An Error-Free Code Example That Runs Successfully

In the example above, we made a mistake on the code intentionally to understand how the code works. If we correct it like below:

@echo off
ECHO Running a Batch file
CALL "G:BATCHYourfile.bat"
IF  errorlevel 1 GOTO ERROR
ECHO The file runs successfully.
GOTO EOF

:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1

:EOF

Then we will get an output like this:

Running a Batch file
This is from the first file
The file runs successfully.

Remember, all commands we discussed here are only for the Windows Command Prompt or CMD environment.

Поделиться

Нашли опечатку?

Пожалуйста, сообщите об этом — просто выделите ошибочное слово или фразу и нажмите Shift Enter.

Как правильно обрабатывать коды возврата из программ с помощью ERRORLEVEL Печать

Добавил(а) microsin

  

Раньше я не знал, как правильно использовать в командных файлах (расширение .bat) ERRORLEVEL вместе с оператором ветвления IF. Из-за этого у меня возникали ошибки при написании командных файлов.

Статья была переписана после того, как мне в комментарии указали на ошибку. В справке по команде (см. help if) подробно описывается алгоритм работы IF ERRORLEVEL. Команда предназначена для анализа кода возврата последней запущенной из bat-файла программы, и предпринимать по их значениям нужные действия. Чтобы команда работала правильно, нужно начинать проверять коды возврата с наибольших возможных значений, например так:
program0_4.exe
if errorlevel 4 goto error4
if errorlevel 3 goto error3
if errorlevel 2 goto error2
if errorlevel 1 goto error1
goto ok

Есть также возможность прямой проверки значения кода возврата, если использовать в командном файле переменную %ERRORLEVEL% (работает только в том случае, если Вы не умудрились задать переменную окружения с таким же именем). Переменная %ERRORLEVEL% разворачивается в текстовое значение кода возврата, что в позволяет использовать в командном файле конструкции типа:
goto answer%ERRORLEVEL%
:answer0
echo Получен код возврата 0
:answer1
echo Получен код возврата 1

 

Старый текст статьи

ERRORLEVEL 0 в командных файлах отрабатывается неправильно 

Предположим, программа program0_4.exe на выходе выдает коды возврата от 0 до 4, и код возврата 0 означает, что ошибок не было. Нужно отфильтровать оператором if факт отсутствия ошибки. В этом случае нельзя использовать проверку if errorlevel 0, так как результат этой проверки не всегда верен. Пример1 не работает, а Пример2 работает нормально.

rem Пример 1 — почему-то иногда НЕ РАБОТАЕТ
program0_4.exe
if errorlevel 0 goto ok
echo «Error!»
goto exit

:ok
echo «O.K.»

:exit

rem Пример 2 — работает нормально
program0_4.exe
if errorlevel 1 goto error
if errorlevel 2 goto error
if errorlevel 3 goto error
if errorlevel 4 goto error
goto ok

:ok
echo «O.K.»
goto exit

:error
echo «Error!»

:exit

Добавить комментарий


By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly.

Following are the common exit code and their description.

Error Code Description
0 Program successfully completed.
1 Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe.
2 The system cannot find the file specified. Indicates that the file cannot be found in specified location.
3 The system cannot find the path specified. Indicates that the specified path cannot be found.
5 Access is denied. Indicates that user has no access right to specified resource.

9009

0x2331

Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action.

221225495

0xC0000017

-1073741801

Not enough virtual memory is available.

It indicates that Windows has run out of memory.

3221225786

0xC000013A

-1073741510

The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user’s keyboard input CTRL+C or CTRL+Break or closing command prompt window.

3221225794

0xC0000142

-1073741502

The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize.

Error Level

The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.

By default, the way to check for the ERRORLEVEL is via the following code.

Syntax

IF %ERRORLEVEL% NEQ 0 ( 
   DO_Something 
)

It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file.

EXIT /B at the end of the batch file will stop execution of a batch file.

Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.

Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers.

Let’s look at a quick example on how to check for error codes from a batch file.

Example

Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9.

if not exist c:lists.txt exit 7 
if not defined userprofile exit 9 
exit 0

Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0.

Call Find.cmd

if errorlevel gtr 0 exit 
echo “Successful completion”

Output

In the above program, we can have the following scenarios as the output −

  • If the file c:lists.txt does not exist, then nothing will be displayed in the console output.

  • If the variable userprofile does not exist, then nothing will be displayed in the console output.

  • If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt.

Loops

In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements.

S.No Loops & Description
1 While Statement Implementation

There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels.

2 For Statement — List Implementations

The «FOR» construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values.

3 Looping through Ranges

The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement.

4 Classic for Loop Implementation

Following is the classic ‘for’ statement which is available in most programming languages.

Looping through Command Line Arguments

The ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments.

Example

@ECHO OFF 
:Loop 

IF "%1"=="" GOTO completed 
FOR %%F IN (%1) DO echo %%F 
SHIFT 
GOTO Loop 
:completed

Output

Let’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3.

1 
2 
3
S.No Loops & Description
1 Break Statement Implementation

The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop.

  • Overview
  • Part 1 – Getting Started
  • Part 2 – Variables
  • Part 3 – Return Codes
  • Part 4 – stdin, stdout, stderr
  • Part 5 – If/Then Conditionals
  • Part 6 – Loops
  • Part 7 – Functions
  • Part 8 – Parsing Input
  • Part 9 – Logging
  • Part 10 – Advanced Tricks

Today we’ll cover return codes as the right way to communicate the outcome of your script’s execution to the world. Sadly, even
skilled Windows programmers overlook the importance of return codes.

Return Code Conventions

By convention, command line execution should return zero when execution succeeds and non-zero when execution fails. Warning messages
typically don’t effect the return code. What matters is did the script work or not?

Checking Return Codes In Your Script Commands

The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script. A very helpful feature is
the built-in DOS commands like ECHO, IF, and SET will preserve the existing value of %ERRORLEVEL%.

The conventional technique to check for a non-zero return code using the NEQ (Not-Equal-To) operator of the IF command:

IF %ERRORLEVEL% NEQ 0 (
  REM do something here to address the error
)

Another common technique is:

IF ERRORLEVEL 1 (
  REM do something here to address the error
)

The ERRORLEVEL 1 statement is true when the return code is any number equal to or greater than 1. However, I don’t use this technique because
programs can return negative numbers as well as positive numbers. Most programs rarely document every possible return code, so I’d rather explicity
check for non-zero with the NEQ 0 style than assuming return codes will be 1 or greater on error.

You may also want to check for specific error codes. For example, you can test that an executable program or script is in your PATH by simply
calling the program and checking for return code 9009.

SomeFile.exe
IF %ERRORLEVEL% EQU 9009 (
  ECHO error - SomeFile.exe not found in your PATH
)

It’s hard to know this stuff upfront – I generally just use trial and error to figure out the best way to check the return code of the program or
script I’m calling. Remember, this is duct tape programming. It isn’t always pretty, but, it gets the job done.

Conditional Execution Using the Return Code

There’s a super cool shorthand you can use to execute a second command based on the success or failure of a command. The first program/script must
conform to the convention of returning 0 on success and non-0 on failure for this to work.

To execute a follow-on command after sucess, we use the && operator:

SomeCommand.exe && ECHO SomeCommand.exe succeeded!

To execute a follow-on command after failure, we use the || operator:

SomeCommand.exe || ECHO SomeCommand.exe failed with return code %ERRORLEVEL%

I use this technique heavily to halt a script when any error is encountered. By default, the command processor will continue executing
when an error is raised. You have to code for halting on error.

A very simple way to halt on error is to use the EXIT command with the /B switch (to exit the current batch script context, and not the command
prompt process). We also pass a specific non-zero return code from the failed command to inform the caller of our script about the failure.

SomeCommand.exe || EXIT /B 1

A simliar technique uses the implicit GOTO label called :EOF (End-Of-File). Jumping to EOF in this way will exit your current script with
the return code of 1.

SomeCommand.exe || GOTO :EOF

Tips and Tricks for Return Codes

I recommend sticking to zero for success and return codes that are positive values for DOS batch files. The positive values are a good idea
because other callers may use the IF ERRORLEVEL 1 syntax to check your script.

I also recommend documenting your possible return codes with easy to read SET statements at the top of your script file, like this:

SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_FILE_NOT_FOUND=2

Note that I break my own convention here and use uppercase variable names – I do this to denote that the variable is constant and should not
be modified elsewhere. Too bad DOS doesn’t support constant values like Unix/Linux shells.

Some Final Polish

One small piece of polish I like is using return codes that are a power of 2.

SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_FILE_NOT_FOUND=2
SET /A ERROR_FILE_READ_ONLY=4
SET /A ERROR_UNKNOWN=8

This gives me the flexibility to bitwise OR multiple error numbers together if I want to record numerous problems in one error code.
This is rare for scripts intended for interactive use, but, it can be super helpful when writing scripts you support but you don’t
have access to the target systems.

@ECHO OFF
SETLOCAL ENABLEEXTENSIONS

SET /A errno=0
SET /A ERROR_HELP_SCREEN=1
SET /A ERROR_SOMECOMMAND_NOT_FOUND=2
SET /A ERROR_OTHERCOMMAND_FAILED=4

SomeCommand.exe
IF %ERRORLEVEL% NEQ 0 SET /A errno^|=%ERROR_SOMECOMMAND_NOT_FOUND%

OtherCommand.exe
IF %ERRORLEVEL% NEQ 0 (
    SET /A errno^|=%ERROR_OTHERCOMMAND_FAILED%
)

EXIT /B %errno%

If both SomeCommand.exe and OtherCommand.exe fail, the return code will be the bitwise combination of 0x1 and 0x2, or decimal 3. This return code tells
me that both errors were raised. Even better, I can repeatedly call the bitwise OR with the same error code and still interpret which errors were
raised.


<< Part 2 – Variables


Part 4 – stdin, stdout, stderr >>

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Обработчик заданий печати возвратил код ошибки win32 0x3f
  • Обработчик заданий печати возвратил код ошибки win32 0x0
  • Обработчик 1c web service extension код ошибки 0x800700c1
  • Обработчик 1c web service extension код ошибки 0x80004005

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии