Recommended Posts
-
- Share
Hello,
i have a quick and simple question.
Is someting like this possible :
If @error = 00 Then
MsgBox(0,»test», «00 : » )
ElseIf @error = 230 Then
MsgBox(0 ,»test»,»230 : «)
EndIf
Because i need to use the errorcode for moving on in my script.
Thank you !
Link to comment
Share on other sites
-
- Share
“They did not know it was impossible, so they did it” ― Mark Twain
Link to comment
Share on other sites
- Author
-
- Share
For errorcode 00 it is working. But for errorcode 230 not.
It only shows me the msg box for case 0 and not 230
FileChangeDir(«C:\Program Files\SEH Computertechnik GmbH\SEH UTN Manager»)
RunWait(@ComSpec & » /c » & «utnm.exe»)
Global $test = RunWait(@ComSpec & » /c » & ‘utnm /c «activate xxxxxx 11» /k «BAUMANAGER»‘)
MsgBox(0,»test», «Error : » & $test & @error)
Switch @error
Case 230
MsgBox(0,»Funkt», «23 : «)
Case 00
MsgBox(0,»Funkt», «00 : «)
EndSwitch
Link to comment
Share on other sites
-
- Share
In all scripts, the best way to avoid all this headache is to transfer @error in a variable, immediately after the line you want to test if it succeeded or not, for example :
Global $test = RunWait(...) $iKeep_error = @error ; now you can check $iKeep_error wherever you like
-
Musashi
-
1
Link to comment
Share on other sites
-
- Share
@error is set by the last executed function. In you case, @error is set to 0 by MsgBox. Remove the MsgBox line after the RunWait function :
RunWait(@ComSpec & " /c " & "utnm.exe") Global $test = RunWait(@ComSpec & " /c " & 'utnm /c "activate xxxxxx 11" /k "BAUMANAGER"') ; MsgBox(0,"test", "Error : " & $test & @error) Switch @error Case 230 MsgBox(0,"Funkt", "23 : ") Case 0 MsgBox(0,"Funkt", "00 : ") EndSwitch
edit : in the same time with pixelsearch 😀
Edited by jguinch
Link to comment
Share on other sites
- Author
-
- Share
It is only using case 00 and not 230.
I am really new to this.
So i changed the order of the Case and the script is always using case 2 ( case 0 ) no matter which errorcode is in it.
Link to comment
Share on other sites
-
- Share
5 minutes ago, pixelsearch said:
In all scripts, the best way to avoid all this headache is to transfer @error in a variable, immediately after the line you want to test if it succeeded or not, for example :
4 minutes ago, jguinch said:
@error is set by the last executed function.
@Marcel2304 : These tips are really important. Even if a function like e.g. ConsoleWrite does not provide an error code (according to the help), @error will be reseted.
Example :
; 1 : FileRead(@ScriptDir & "\blabla.txt") ; <-- a file, that does not exist ConsoleWrite("Error = " & @error & @CRLF & @CRLF) ; <-- Error = 1 ; 2 : FileRead(@ScriptDir & "\blabla.txt") ; <-- a file, that does not exist ConsoleWrite("Output :" & @CRLF) ConsoleWrite("Error = " & @error & @CRLF & @CRLF) ; <-- Error = 0 ; 3 : save @error in a var (mentioned by @pixelsearch): Local $iError FileRead(@ScriptDir & "\blabla.txt") ; <-- a file, that does not exist $iError = @error ConsoleWrite("Output :" & @CRLF) ConsoleWrite("Error = " & $iError & @CRLF) ; <-- Error = 1
-
pixelsearch
-
1
«In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move.»
Link to comment
Share on other sites
- Author
-
- Share
I get that but what i don’t unterstand is why only case 0 is triggerd even when its case 230.
Link to comment
Share on other sites
-
- Share
Because you (probably) got a line that resets @error to 0, after your last RunWait and before the Switch line. Could you please tell us what happens if you script it like this and what is written in the Console Window ?
FileChangeDir("C:\Program Files\SEH Computertechnik GmbH\SEH UTN Manager") RunWait(@ComSpec & " /c " & "utnm.exe") Global $test = RunWait(@ComSpec & " /c " & 'utnm /c "activate xxxxxx 11" /k "BAUMANAGER"') Local $iKeep_error = @error ; to be placed here, immediately after RunWait() line ConsoleWrite("$iKeep_error = " & $iKeep_error & @CRLF) MsgBox(0, "Result", "Test = " & $test & " Error = " & $iKeep_error) Switch $iKeep_error Case 230 MsgBox(0,"Funkt", "230 : ") Case 0 MsgBox(0,"Funkt", "0 : ") Case Else MsgBox(0,"Funkt", $iKeep_error) EndSwitch
Edited by pixelsearch
Added a Case Else, in case of…
Link to comment
Share on other sites
-
- Share
Something else read in the help file, topic RunWait :
Return Value Success: the exit code of the program that was run. Failure: sets the @error flag to non-zero.
So what is this 230 you mention ?
If 230 is the correct return value you’re expecting, then it has nothing to do with @error, which will be 0 if RunWait succeeded (returning 230)
Link to comment
Share on other sites
-
- Share
«In the beginning the Universe was created. This has made a lot of people very angry and been widely regarded as a bad move.»
Link to comment
Share on other sites
Create an account or sign in to comment
You need to be a member in order to leave a comment
Sign in
Already have an account? Sign in here.
Sign In Now
Завершает выполнение скрипта.
Этот код может быть получен при использовании функции OnAutoItExitRegister с помощью
См. также
; пример 1
Exit
; пример 2
; Скрипт завершается, если нет каких-нибудь параметров командной строки
If $CmdLine[0] = 0 Then Exit (1)
; пример 3
; Открывает файл, указанный в первом параметре командной строки
$file = FileOpen($CmdLine[1], 0)
; Проверяет, открылся ли файл
If $file = —1 Then Exit (2)
; Если файл пуст — выход
$line = FileReadLine($file)
If @error = —1 Then Exit
; какой-нибудь код обработки файла
FileClose($file)
Exit ; команда в последней строке скрипта, хотя необязательна
My AutoIt script generates an error that I want to handle. A way that any error goes to a custom function will also do. In VBA I use OnErrorGoTo
, but I am unable to find something similar in AutoIt.
My Code :
Func Start()
While 1
If ProcessExists ( "Photoshop.exe" ) <> 0 Then
Sleep(5000)
Else
Local $sFile ="C:\Auto\CodeToBe\Batch\Image Process-50-2D v.2-" & $n & ".jsxbin"
Local $iPID = ShellExecute($sFile)
Sleep(10000)
$n = $n+1
EndIf
WEnd
EndFunc
An error will occur when $n
exceeds the number of files in that folder. I tried this but didn’t work (from the «HELP SECTION» and a forum post):
Global $iEventError = 0 ; To be checked to know if COM error occurs. Must be reset after handling.
Local $oMyError = ObjEvent("AutoIt.Error", "ErrFunc") ; Install a custom error handler
Func Start()
While 1
If ProcessExists ( "Photoshop.exe" ) <> 0 Then
Sleep(5000)
Else
Local $sFile ="C:\Auto\CodeToBe\Batch\Image Process-50-2D v.2-" & $n & ".jsxbin"
Local $iPID = ShellExecute($sFile)
If $iEventError Then
MsgBox($MB_OK, "", "There was an error on the previous line.")
$iEventError = 0 ; Reset after displaying a COM Error occurred
EndIf
Sleep(10000)
$n = $n+1
EndIf
WEnd
EndFunc
; This is my custom error handler
Func MyErrFunc()
Msgbox(0,"","ERROR GENERATED ON " & $n)
Endfunc
user4157124
2,80313 gold badges27 silver badges42 bronze badges
asked Nov 30, 2015 at 9:33
2
I recommend the second example because it prevents an error in the first place. However, the first example can be used as a general error checker.
Example 1
Start()
Func Start()
Local $n = 1
While 1
If ProcessExists("Photoshop.exe") <> 0 Then
Sleep(5000)
Else
Local $sFile = "C:\Auto\CodeToBe\Batch\Image Process-50-2D v.2-" & $n & ".jsxbin"
Local $iPID = ShellExecute($sFile)
If @error Then MyErrFunc(@ScriptLineNumber, @error) ;check for error
Sleep(10000)
$n = $n + 1
EndIf
WEnd
EndFunc ;==>Start
; error handler
Func MyErrFunc($iLineNumer, $iError)
$iLineNumer = $iLineNumer - 1
MsgBox(0, "", "ERROR GENERATED ON SCRIPT LINE: " & $iLineNumer & @CRLF & "ERROR CODE: " & $iError)
EndFunc ;==>MyErrFunc
Example 2
Start2()
Func Start2()
Local $n = 1
While 1
If ProcessExists("Photoshop.exe") <> 0 Then
Sleep(5000)
Else
Local $sFile = "C:\Auto\CodeToBe\Batch\Image Process-50-2D v.2-" & $n & ".jsxbin"
If FileExists($sFile) Then
Local $iPID = ShellExecute($sFile)
Sleep(10000)
Else ;handle error (you could use a function here if you wanted)
ConsoleWrite("File not found: " & $sFile & @CRLF)
EndIf
$n = $n + 1
EndIf
WEnd
EndFunc ;==>Start2
user4157124
2,80313 gold badges27 silver badges42 bronze badges
answered Nov 30, 2015 at 14:20
MrAutoItMrAutoIt
7856 silver badges21 bronze badges
Try to implement error checking.
If Not FileExists(your string with the $n) Then
... abort
Else
shellexecute ...
You could use _FileListToArray()
instead.
user4157124
2,80313 gold badges27 silver badges42 bronze badges
answered Nov 30, 2015 at 10:13
XenobiologistXenobiologist
2,0911 gold badge12 silver badges16 bronze badges
1
An error will occur when
$n
exceeds the number of files in that folder.
As per Documentation — Function Reference — _FileListToArray()
:
Lists files and\or folders in a specified folder (Similar to using Dir with the /B Switch)
Will loop over existing filenames only (avoiding error altogether). Example:
#include <File.au3>
Global Const $g_sPathFiles = 'C:\Auto\CodeToBe\Batch\'
Global Const $g_sMaskFile = '*.jsxbin'
Global Const $g_aFile = _FileListToArray($g_sPathFiles, $g_sMaskFile, $FLTA_FILES, True)
For $i1 = 1 To $g_aFile[0]
ShellExecuteWait($g_aFile[$i1])
Next
Alternatively _FileListToArrayRec()
may be used.
Related.
answered Jun 22, 2018 at 3:01
user4157124user4157124
2,80313 gold badges27 silver badges42 bronze badges
Нашли строку, но не знаете что с ней делать? Поставьте перед сбойной строкой MsgBox с выводом значения переменной, чтоб увидеть, являются ли данные тем, что необходимо получить. И если переменная является массивом, то используйте _ArrayDisplay, добавив в начало скрипта
Если скрипт был найден на форуме, то попытайтесь выяснить версию AutoIt3, с которой использовался скрипт, например по дате поста. Проверьте чтобы все необходимые скрипту
Если окно ошибки указывает на переменную являющуюся элементом массива, даже если вы уверены что с массивом всё в порядке, то очень вероятно, что цикл использует индекс превышающий существующие индексы в массиве. Используйте
Ниже приведен полный список фатальных ошибок AutoIt, возникающих при неправильном написании скриптов пользователем. Всего 74
Вот несколько новых простых методов, которые должны помочь решить, я бы сказал, проблему с автоматической обработкой ошибок.
Привет всем, это личное сообщение является отправной точкой здесь. Я новичок в Autoit, а также только что поднял его в прошлом месяце. В настоящее время я работаю над проектом по автоматизации нашего собственного процесса загрузки выписки финансового учреждения с веб-сайта банка. Настоящая проблема, которую я покупаю, заключается в подготовке к устранению неполадок, когда возникает ошибка из-за сбоя / тайм-аута определенного веб-сайта. Я генерирую, чтобы перехватить событие ошибки, когда одно из наиболее часто связанных с ними событий выходит из строя с моими функциями _IE, потому что заполнение страницы зависло.
FuncTest()Локальный $oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc")$WinHandle эквивалентно WinGetHandle("тестовый сайт")$oIE означает _IEAttach($WinHandle, "hwnd")$oFrame = _IEFrameGetObjByName($oIE, "leftFrame")$oDiv = _IEGetObjById($oFrame, "divFoldCont")$oDiv2 почти наверняка равен _IEGetObjById($oDiv, "divFold0")$oDiv3 = _IEGetObjById($oDiv2,"divFoldSub0_1")$oLinks равно _IELinkClickByText($oDiv3, "Выписка по счету")Спящий режим (1000) НО; Введите номер грида$oFrame = _IEFrameGetObjByName($oIE, "рабочая область")$oLinks = _IELinkGetCollection($oFrame) Для $oLink $oLinksНО; ConsoleWrite($oLink.href)_IEAction($oLink, "щелчок")сон (1000)Выходной цикл Далеерадио конецФункция _ErrFunc($oError)$ErrorMessage = (@ScriptName & cm ("& $oError.scriptline &"): ! ==> Обнаружена ошибка COM!"&@CRLF&_@TAB & "err.number": & @TAB & @TAB & "0x" & Hex($oError.number) @CRLF & & _@TAB & "err.windescription:" & @TAB & $oError.win & @CRLF схема & _@TAB & "err.description: расстояние в дюймах & @TAB & $oError.& введите @CRLF & _@TAB & "err.source: & inch @TAB & @TAB & $oError.source & @CRLF & _@TAB & "err.Is: файл справки" & @TAB & $oError.helpfile & @CRLF & _@TAB & "err.helpcontext: ширина внутри дюймов & @TAB & $oError.helpcontext & @CRLF & _@TAB & "err.lastdllerror is: & " @TAB & $oError.lastdllerror & @CRLF & _& @tab "err.scriptline превратится в: " && @tab $oError.scriptline & @CRLF & _@TAB & "err.retcode: " @TAB & & "0x" & Hex($oError.retcode) & @CRLF & @CRLF)EndFunc ;==>_ErrFunc
Я ожидал, что тип программы автоматически отправит мне существенное электронное письмо, чтобы сообщить мне, что процесс на самом деле не удался. Это электронное письмо выдается при обнаружении очень ошибочного события. Однако в этом и заключается условие. Мой сценарий все еще может поймать правильное сообщение об ошибке, если все работает. Во время _IEAttach появляется сигнал об ошибке.
–> Предупреждение функции IE.au3 T3.0-2 _IEAttach, невозможно зарегистрировать встроенную ошибку, невозможно перехватить ошибки COM (используйте _IEErrorHandlerRegister() с регистрацией пользовательского обработчик ошибок)
Как изменить сценарий, чтобы эта выборочная ошибка не запускала функцию обработки ошибок?
П.С. Я открыт для предложений по улучшению моего сценария.
P.S.S. Я не могу использовать _IECreate, потому что мне нужно войти на сайт с помощью физического одноразового пароля, поэтому мне в основном нужно войти на сайт онлайн перед запуском скрипта.
<цитата блока>
37 минут внутри jdelaney сказал:
Добавьте обработчик ошибок. Иногда, когда доминантный объект недоступен, при попытке помочь получить дочернее свойство или объект запись вступает в силу. _ieerrorhandlerregister, в любом случае.
Я нашел это практически через любой поиск Google и экспериментирую с ним. Достаточно того, что я выберу вашу пустую функцию, верно? Предположим, я хочу, чтобы вы ничего не могли сделать, кроме как игнорировать, см. ошибку. По идее мой цикл do-intil сделает все
РЕДАКТИРОВАТЬ: Ближе, хотя какой бы текст я ни пробовал, я помещаю его в консоль, и программа вылетает. Но кажется, по крайней мере, поймать эту отчетливую ошибку
>”C:Program FilesAutoIt3SciTE..autoit3.exe” /ErrorStdOut “C:Scriptsxxx.au3”
–> Запуск IE.au3 T3.0-2 из предупреждения _IETableGetCollection, $_IESTATUS_NoMatch
–> Задание IE.au3 T3.0-2 прервано из-за ошибки _IETableWriteToArray, $_IESTATUS_InvalidDataType
–> IE.au3 T3.0-2 Работа будет выполняться предупреждением _IETableGetCollection, $_IESTATUS_NoMatch
–> IE.au3 T3.0-2 Ошибка отображения результатов _IETableWriteToArray, $_IESTATUS_InvalidDataType
–> IE.au3 T3.0-2 Из пункта предупреждения _IETableGetCollection, $_IESTATUS_NoMatch
–> IE.au3 T3.0-2 Операционная ошибка $_IESTATUS_InvalidDataType
_ietablewritetoarray,
г.