OnError

Registers a function to be called automatically whenever an unhandled error occurs.

OnError Callback , AddRemove

パラメータ

Callback

型:機能オブジェクト

The function to call.

The callback accepts two parameters and can be defined as follows:

MyCallback(Thrown, Mode) { ...

パラメータに与える名前は重要ではないが、以下の値が順次割り当てられる:

  1. 投げられた値(通常はErrorオブジェクト)。
  2. The error mode: Return, Exit, or ExitApp. For details, see the table below.

対応する情報が不要な場合、コールバックのパラメータリストの最後から1つ以上のパラメータを省略することができますが、この場合、MyCallback(Param1, *)のように、最後のパラメータとしてアスタリスクを指定する必要があります。

The callback can return one of the following values (other values are reserved for future use and should be avoided):

AddRemove

型:整数

省略されたときは、初期値は 1 です。それ以外の場合は、次のいずれかの番号を指定してください:

Error Modes

Mode 説明
リターン The thrown value is a continuable runtime error. コールバックが-1を返した場合はスレッドを継続し、それ以外の場合はスレッドを終了します。
Exit The thrown value is a non-continuable runtime error or a value thrown by the script. スレッドが終了します。
ExitApp The thrown value is a critical runtime error, such as corruption detected by DllCall. プログラムが終了します。

備考

Callback is called only for errors or exceptions which would normally cause an error message to be displayed. OnErrorはスクリプトがロードされた後でないと呼び出せないため、ロードタイムエラーでは呼び出せません。

Callback is called on the current thread, before it exits (that is, before the call stack unwinds).

Try, Catch, Throw, OnExit

スクリプトによって発生したエラーをユーザーに表示するのではなく、テキストファイルにログを記録します。

OnError LogError
i := Integer("cause_error")

LogError(exception, mode) {
    FileAppend "Error on line " exception.Line ":" exception.Message "`n"
        , "errorlog.txt"
    return true
}

OnErrorを使用して、代替のエラー処理方法を実装します。Caveat:Tryが有効な間はOnErrorは無効です。

AccumulateErrors()
{
    local ea := ErrorAccumulator()
    ea.Start()
    return ea
}

class ErrorAccumulator
{
    Errors := []                        ; Array for accumulated errors.
    _cb := AccumulateError.Bind(this.Errors)
    Start() => OnError(this._cb, -1)    ; Register our cb before others.
    Stop() => OnError(this._cb, 0)      ; Unregister our cb.
    Last => this.Errors[-1]             ; Most recent error.
    Count => this.Errors.Length         ; Number of accumulated errors.
    __item[i] => this.Errors[i]         ; Shortcut for indexing.
    __delete() => this.Stop()           ; For tying to function scope.
}

; This is the OnError callback. 'errors' is given a value via Bind().
AccumulateError(errors, e, mode)
{
    if mode != "Return" ; Not continuable.
        return
    if e.What = "" ; Expression defect or similar, not a built-in function.
        return
    try {
        ; Try to print the error to stdout.
        FileAppend Format("{1} ({2}) : ({3}) {4}`n", e.File, e.Line, e.What, e.Message), "*"
        if HasProp(e, "extra")
            FileAppend "     Specifically:" e.Extra "`n", "*"
    }
    errors.Push(e)
    return -1 ; Continue.
}

RearrangeWindows()
{
    ; Start accumulating errors in 'err'.
    local err := AccumulateErrors()

; Do some things that might fail...
    MonitorGetWorkArea , &left, &top, &right, &bottom
    width := (right-left)//2, height := bottom-top
    WinMove left, top, width, height, A_ScriptFullPath
    WinMove left+width, top, width, height, "AutoHotkey v2 Help"

; Check if any errors occurred.
    if err.Count
        MsgBox err.Count " error(s); last error at line #" err.Last.Line
    else
        MsgBox "No errors"

; Stop is called automatically when the variable goes out of scope,
    ; since only we have a reference to the object.  This causes OnError
    ; to be called to unregister the callback.
;err.Stop()
}

; Call the test function which suppresses and accumulates errors.
RearrangeWindows()
; Call another function to show normal error behaviour is restored.
WinMove 0, 0, 0, 0, "non-existent window"