OnError

Specifies a function to run automatically when an unhandled error occurs.

OnError Func , AddRemove

Parameters

Func

Type: String or Object

A function name or function object to call when an unhandled error occurs. See Callback below.

AddRemove

Type: Integer

One of the following values:
1 (the default): Call the function after any previously registered functions.
-1: Call the function before any previously registered functions.
0: Do not call the function.

Callback

The callback function should accept two parameters:

Callback(Thrown, Mode)
Thrown
Thrown is the thrown value, usually an exception object.
Mode
One of the following strings:

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

Remarks

Func is called only for errors or exceptions which would normally cause an error message to be displayed. It cannot be called for a load-time error, since OnError cannot be called until after the script has loaded.

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

Related

Try, Catch, Throw, OnExit

Examples

#1: Logging errors to a text file instead of displaying them to the user.

OnError "LogError"
i := Integer("cause_error")

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

#2: Use OnError to implement alternative error handling methods. Caveat: OnError is ineffective while Try is active.

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

class ErrorAccumulator
{
    Errors := []                        ; Array for accumulated errors.
    _cb := Func("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 function. '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"