Bat обработка ошибок

Поделиться

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

Пожалуйста, сообщите об этом — просто выделите ошибочное слово или фразу и нажмите 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

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

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:\BATCH\Yourfile.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.

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

161k26 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

128k28 gold badges253 silver badges391 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:\mypath\myexe.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:\mypath\myexe.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,6483 gold badges40 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

711 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

412 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

I am just starting to learn how to script. I’m trying to understand how the system handles Error Levels and how they can be used in error handling. I know there is a difference between the environment variable %ERRORLEVEL% and the Error Level of the system. If I understand this correctly, then the
If ERRORLEVEL 1
code would check the environment variable before it checks the error level of the previous command.

So, in my program I am trying to interface a startup/stop script that will start/stop all scripts of a given machine (for testing I’m just using one application notepad.exe as an example). I have two wrapper scripts that will either start up or stop the applications by passing arguments to the independent script. If there is an error in the independent script, it will set the errorlevel using the
EXIT /B n

command. Once control is returned to the calling script, it will go to an error handling script if the exit status is non-zero.

At first I was setting the %ERRORLEVEL% to zero manually and then testing for an error after a START or TASKKILL command. But then I read that clearing %ERRORLEVEL% with
SET ERRORLEVEL=
is a better method. My issue comes in when I try to start the app with

START "" notepad.exe

Whenever I test the errorlevel after this command it is always greater than or equal to 1 unless I use SET ERRORLEVEL=0 before I run the start command. I have inserted the code for the four scripts below. Any insight and advice would be greatly appreciated.

appstart.bat:

@echo off
:: Script for application Start
set ERRORLEVEL=
:: ****
:: Additional Batch files will be executed from within this file
:: Example: 
::     Call Appbat01.bat
:: The called batch file should set ERRORLEVEL non-zero if error
:: ****

call test.bat -start
if ERRORLEVEL 1 (call error.bat) 
echo.
echo Control was returned to appstart.bat...
:: **** End Calls
goto end

:end

appstop.bat:

@echo off
:: Script for application Start
set ERRORLEVEL=
:: ****
:: Additional Batch files will be executed from within this file
:: Example: 
::     Call Appbat01.ba
:: The called batch file should set ERRORLEVEL non-zero if error
:: ****

call test.bat -stop
if ERRORLEVEL 1 (call error.bat) 
echo.
echo Control was returned to appstop.bat...
:: **** End Calls
goto end

:end

test.bat:

@echo off
if "%1"=="-start" goto :start
if "%1"=="-stop" goto :stop
goto wrongParams

:start
::****
:: Insert start up stripts here...
:: If there is an error, set ERRORLEVEL=1
::****
    set ERRORLEVEL=0
    echo.
    echo ********
    echo starting the service...
    echo.
    ::start "" "C:\Program Files\Microsoft Office\office11\winword.exe"
    start notepad.exe
    if ERRORLEVEL 1 goto error
    qprocess notepad.exe
    echo *Start.success* ERRORLEVEL is: %ERRORLEVEL%
    echo.
    goto end

:stop
::****
:: Insert stopping stripts here...
:: If there is an error, set ERRORLEVEL>1
::****
    set ERRORLEVEL=0
    echo.
    echo ********
    echo stopping the service...
    echo.
    qprocess notepad.exe 
    taskkill /f /im notepad.exe
    if ERRORLEVEL 1 goto noProcess
    goto end

:noProcess
    set ERRORLEVEL=2
    echo *noProcess* ERRORLEVEL is now: %ERRORLEVEL%
    echo.
    exit /b 2
:error
:: Errorhandler. Log application status and cause of error here. Set
:: ERRORLEVEL > 1 before returning to caller. 
    set ERRORLEVEL=1
    echo.
    echo **** Error handler inside test.bat ****
    echo.
    echo *error* ERRORLEVEL is now: %ERRORLEVEL%
    echo.
    exit /b 1

:wrongParams
:: Output an error if the wrong parameters were passed to this script.
:: Maybe try to self correct the parameter...
    set ERRORLEVEL=1
    echo.
    echo '%1' is an invalid parameter.
    echo Usage: %0 [-stop ^| -start] 
    echo *wrongParams* ERRORLEVEL is now: %ERRORLEVEL%
    echo.
    exit /b 1
:end

error.bat:

@echo off
echo **** You have reached error.bat ****
echo ERRORLEVEL inside of error.bat is: %ERRORLEVEL%
echo.
::*** Handle error...***
goto error%ERRORLEVEL%

:error2
    echo The process could not be stopped for some reason.
    goto end
:error1
    echo The process had an error in start up.
::***                ***
    goto end

:end

Как сделать обработку исключений в CMD?
В python например так:

try:
  ... 
  print("Ошибок нет! ") 
except:
  print("Ошибка!")


  • Вопрос задан

  • 617 просмотров

КОМАНДА1 && КОМАНДА2
— вторая команда выполняется, если первая завершилась без ошибок.
КОМАНДА1 || КОМАНДА2
— вторая команда выполняется, если первая завершилась с ошибкой.

КОМАНДА && echo Ошибок нет! || echo Ошибка!

(Для объединения нескольких команд в составную можно использовать скобки, переносы строк или знак & между командами в одной строке. Для размещения одной простой команды на нескольких строках можно использовать ^ в конце переносимой строки…)

Пригласить эксперта


  • Показать ещё
    Загружается…

VK

Москва

от 200 000 до 500 000 ₽

ЛАНИТ

Санкт-Петербург

от 80 000 ₽

21 сент. 2023, в 10:41

5000 руб./за проект

21 сент. 2023, в 10:18

1000 руб./за проект

21 сент. 2023, в 09:45

1000 руб./за проект

Минуточку внимания

Понравилась статья? Поделить с друзьями:
  • Bash игнорировать ошибку
  • Bat игнорировать ошибки
  • Bash это каталог ошибка
  • Bad host ошибка
  • Baltur котел газовый ошибка e72