Quick answer: Call exception_unhandled_handler(function(_ex) { ... }) once at game start. GameMaker runs your function when an error is not caught by any try/catch, passing a struct with message, longMessage, script and stacktrace, and closes the game when the function returns. Because the game closes, an http_request started inside the handler never finishes. Write the error to a file in the save area there, and send it from a controller object the next time the game starts.

By default an unhandled GameMaker error shows the grey “ERROR in action number 1” window, and when the player clicks through, the game is gone. They might screenshot it. Usually they do not, and the text is lost. exception_unhandled_handler lets you run your own code at that moment instead: save the error, show a friendlier message, and make sure the details reach you. This guide covers how the function works, the one limitation that trips up everyone who tries to upload from it, and a complete GameMaker crash handler that saves the crash log and sends it on the next launch.

How exception_unhandled_handler works

The function takes one argument, a function or method that receives the exception:

exception_unhandled_handler(function(_ex) {
    // _ex describes what went wrong
    return 0;
});

It is available in GameMaker 2.3 and later. Three facts shape everything you do with it.

It fires for GML runtime errors (reading a variable that was never set, an array index out of range, an instance that no longer exists, a wrong argument type) and for any value passed to throw that is not caught. It does not fire for crashes below GML, such as running out of memory or a graphics driver fault. Those end the process with no GML code running at all.

What is in the exception struct

For a runtime error, _ex is a struct with these members:

MemberContents
messageA short description of the error
longMessageThe full text, including the object and event it happened in. This is roughly what the default error window shows.
scriptThe name of the script or event where the error was raised
stacktraceAn array of strings, innermost call first, such as gml_Object_obj_player_Step_0 (line 14)

Do not assume the struct is always there. throw accepts any value, so throw "save file corrupt" hands your handler a string, and throw { code: 12 } hands it a struct with none of the members above. Check with is_struct and variable_struct_exists before reading anything. An error inside the error handler is the last thing you want.

Register it once, as early as possible

The handler should exist before any of your objects do. Since GameMaker 2.3, code written at the top level of a script asset, outside any function, runs once when the game starts and before the first room is created. That is the right place: create a script called scr_crash_handler and put the call directly in it. The Create event of a controller in the first room also works, but then errors in other objects’ Create events in that room can happen before the handler is set.

Calling the function again replaces the previous handler. Register it in one place only.

Why http_request does not work inside the handler

The obvious thing to do in a crash handler is post the error to a server. In GameMaker that cannot work from here. http_request does not send anything by itself and wait. It queues a request and returns an ID. The runner does the network work over the following steps and delivers the result to an Async - HTTP event. The handler returns, the game closes, and there are no following steps. The request is abandoned and the Async event never runs.

What does work in the handler is anything that completes immediately: file functions, show_debug_message and show_message. So the reliable design has two halves. Save the error to a file now. Send the file the next time the game starts, when the step loop and Async events are running again.

A crash handler that saves the error to a file

Put this in scr_crash_handler. It defends against non-struct exceptions, builds a title that is stable between players, and writes one JSON file.

/// scr_crash_handler
/// Top-level code in a script asset runs once at game start.

exception_unhandled_handler(function(_ex) {
    var _message = string(_ex);
    var _long = _message;
    var _where = "";
    var _stack = "";

    if (is_struct(_ex)) {
        if (variable_struct_exists(_ex, "message")) _message = string(_ex.message);
        if (variable_struct_exists(_ex, "longMessage")) _long = string(_ex.longMessage);
        if (variable_struct_exists(_ex, "script")) _where = string(_ex.script);
        if (variable_struct_exists(_ex, "stacktrace") && is_array(_ex.stacktrace)) {
            var _count = array_length(_ex.stacktrace);
            for (var _i = 0; _i < _count; _i++) {
                _stack += string(_ex.stacktrace[_i]) + "\n";
            }
            if (_count > 0) _where = string(_ex.stacktrace[0]);
        }
    }

    var _platform = "Other";
    if (os_type == os_windows) _platform = "Windows";
    else if (os_type == os_macosx) _platform = "macOS";
    else if (os_type == os_linux) _platform = "Linux";

    var _title = (_where != "") ? ("Unhandled error in " + _where) : _message;

    var _record = {
        title: string_copy(_title, 1, 200),
        description: _long + "\n\n--- Stack trace ---\n" + _stack
            + "\nRoom: " + room_get_name(room),
        platform: _platform,
        game_version: GM_version
    };

    var _file = file_text_open_write("crash.json");
    file_text_write_string(_file, json_stringify(_record));
    file_text_close(_file);

    show_debug_message("Unhandled exception: " + _long);
    show_message("Sorry, the game ran into an error and has to close.\n"
        + "A report will be sent the next time you start it.");
    return 0;
});

A plain file name goes to the game’s save area, the sandboxed folder GameMaker also uses for save files. On Windows that is %LOCALAPPDATA%\<game name>, and the built-in game_save_id holds the path on every platform. You do not need to build a path yourself.

The title uses the first stack trace entry and leaves the message out. GameMaker error messages often contain instance IDs, which differ on every run, so a title built from the message would make each crash look unique. The location is the same for every player who hits the bug. The full message is still in the description.

show_message blocks until the player dismisses it, which is what you want on desktop. Keep the wording honest and short. If you ship to platforms where a blocking message box is not appropriate, leave it out and let the game close.

Send the saved crash on the next launch

Add a persistent controller object to your first room. Its Create event looks for the file and posts it. The URL, header and field names here are Bugnet’s public submit API, and any HTTP endpoint that accepts JSON works the same way.

/// obj_crash_reporter : Create
crash_request = -1;

if (file_exists("crash.json")) {
    var _buffer = buffer_load("crash.json");
    var _raw = buffer_read(_buffer, buffer_text);
    buffer_delete(_buffer);

    try {
        var _crash = json_parse(_raw);
        var _body = json_stringify({
            title: _crash.title,
            description: _crash.description,
            category: "crash",
            priority: "critical",
            platform: _crash.platform,
            game_version: _crash.game_version
        });

        var _headers = ds_map_create();
        ds_map_add(_headers, "Content-Type", "application/json");
        ds_map_add(_headers, "X-API-Key", "sk_live_your_project_key");
        crash_request = http_request(
            "https://api.bugnet.io/api/bugs/submit", "POST", _headers, _body);
        ds_map_destroy(_headers);
    } catch (_error) {
        // The file is unreadable. Do not retry it on every launch.
        file_delete("crash.json");
    }
}

The result arrives in the same object’s Async - HTTP event. Delete the file only when the server has answered, so a player who was offline sends the report on a later launch instead of losing it.

/// obj_crash_reporter : Async - HTTP
if (async_load[? "id"] != crash_request) exit;
if (async_load[? "status"] == 1) exit;  // still in progress

var _code = async_load[? "http_status"];
if (_code == 200 || _code == 201 || _code == 400) {
    // Delivered, or rejected in a way that will not change on retry.
    file_delete("crash.json");
}
crash_request = -1;

The comparison against crash_request matters as soon as your game makes any other HTTP call, because every request’s result arrives in every Async - HTTP event. This design keeps one crash file, so if the game crashes twice before a report goes out, the newer crash overwrites the older one. For most games that is fine. If you want every crash, add a timestamp to the file name and loop over the matches with file_find_first.

try, catch and finally: for errors you can recover from

The unhandled handler is the safety net. For code that you expect to fail sometimes, catch the error where it happens and carry on. Loading a save file, parsing JSON from a server and reading player-made content are the usual candidates.

var _buffer = buffer_load("save.json");
try {
    var _data = json_parse(buffer_read(_buffer, buffer_text));
    load_game_from(_data);
} catch (_ex) {
    show_debug_message("Save could not be loaded: " + string(_ex.message));
    start_new_game();
} finally {
    buffer_delete(_buffer);
}

The catch block receives the same exception struct. The finally block always runs, error or not, which makes it the place to free buffers and data structures. Because the game keeps running after a catch, async functions work normally there. A report sent from a catch block goes out straight away, with no file needed.

Do not wrap whole Step events in try to hide errors. A swallowed exception leaves the instance half updated, and the bug that eventually surfaces is much harder to trace than the original.

Stack traces, show_debug_message and debug_get_callstack

Stack trace entries follow GameMaker’s internal naming: gml_Object_<object>_<event>_<number> for events and gml_Script_<name> for script functions. Reading from the top, the first entry is where the error was raised and each following one is its caller.

How much detail you get can differ between the VM and YYC exports, since YYC compiles your GML to native code. Trigger a deliberate error in the export you ship and look at what the saved file contains before you rely on it.

show_debug_message output goes to the IDE’s Output window while you develop. Players have no such window, so do not count on it as your record. debug_get_callstack() returns the current call stack as an array of strings at any time, not only during an error. It is useful for breadcrumbs: when something looks wrong but does not throw, log the call stack to a list and include that list in the crash file.

How this fits with the Bugnet GameMaker SDK

The Bugnet GameMaker SDK is a single GML script that runs from a persistent controller object, including an Async - HTTP event that calls bugnet_async_http(). For errors you catch, pass the exception to bugnet_exception_handler(_ex) inside the catch block. It reads message and stacktrace and files a crash report with the platform, the game version, a screenshot when screenshot capture is on, and the recent lines you logged through bugnet_debug_message(), once per distinct message per session, as long as automatic error filing is switched on for the project in the dashboard. The game is still running, so the request completes.

For the unhandled case the SDK uses the same file pattern as this article. bugnet_init() registers its own exception_unhandled_handler, which writes the error, the stack trace and the recent log lines to a file in the save area and shows the error text in a message box. On the next launch, once the project settings have loaded, it files the report and closes the crashed session, so the crash counts against your crash-free rate. With the SDK installed you do not need the handler from this article at all.

GameMaker keeps one unhandled handler at a time. If you want your own, for a friendlier message or to save extra state, pass false as the third argument to bugnet_init() and hand the exception to the SDK from yours:

/// obj_bugnet : Create
bugnet_init("YOUR_API_KEY", "https://api.bugnet.io", false);

exception_unhandled_handler(function(_ex) {
    bugnet_unhandled_exception(_ex);   // saved now, reported on the next launch
    show_message("Sorry, the game ran into an error and has to close.\n"
        + "A report will be sent the next time you start it.");
    return 0;
});

Reports land in a dashboard where identical titles stack with an occurrence count, alongside the bugs players file through the in-game widget. The free plan covers one project and up to 100 bug reports in total. The SDK docs list the controller events the script needs.

Frequently asked questions

What does exception_unhandled_handler do in GameMaker?

It registers a function that GameMaker calls when a runtime error or a thrown value is not caught by any try and catch. The function receives the exception, and when it returns the game closes. It replaces the default error window, so use it to save the error and show your own message.

Can I keep the game running after an unhandled exception in GameMaker?

No. Once the unhandled handler has been called the game ends when it returns. To recover from an error and keep playing, wrap the risky code in try and catch, which stops the exception before it becomes unhandled.

Why does my http_request not send from the crash handler?

http_request is asynchronous. It only starts the request, and the result arrives later in the Async HTTP event. The game closes as soon as the handler returns, so the request is abandoned. Save the error to a file instead and send it the next time the game starts.

What is in the GameMaker exception struct?

For runtime errors it has message, a short description, longMessage, the full text with the event it happened in, script, the script or event name, and stacktrace, an array of strings. A value passed to throw arrives exactly as thrown, which may not be a struct at all.

Where does GameMaker save a crash file I write from the handler?

A plain file name such as crash.json is written to the game’s save area, the same folder as its save files. On Windows that is a folder named after the game under Local AppData. The built-in variable game_save_id holds the full path.

The handler is your last few lines of code before the game closes. Write the error to a file there and send it when the game next starts.