Creating Custom Fatal Error Pages in MODX

MODX has a built in setting named error_page, but that is primarily for just handing 404 type errors when a URL string doesn't match a resource. What happens when your visitors experience other types of errors?

In this article, I will discuss how to add custom error pages to your MODX site and to your MODX Cloud instance.

Create an Error Page

The first thing that you need to do is create an error page. I highly recommend keeping them simple. It should be a single HTML page that gets the point accross. You can take your 400 page as a basic example, but don't include a lot of links to other pages on your site in case there's a major emergency.

Once you have created your page place it is the web root named 500.html. You can name it whatever, but for the following exmaples, we will assume the path is /www/500.html

Set up the Server Rewrite Rules

For this example I will be using nginx, as that is what we use on MODX cloud hosting. You may have different requirements if using another host, but the gist will be similar.

On the MODX cloud dashboard, go to your cloud instance. Click on the "Web Server" tab, and add the following entry to your "Web Rules / Rewrites":

error_page 500 502 503 504 /500.html;

The above will direct "Server" errors to your custom 500.html page. This is helpful in the event of a misconfigured server rule or similar server-side issue.

Set up the PHP Error Handler

MODX uses PHP, which handles it's own errors outside of what the server does. In order to use a custom 500 page on MODX you will need to tell PHP what to do with errors.

In your favorite editor, open up the PHP file located at /www/core/config/config.inc.php. You will need to add an error handler here so it persists between upgrades. At the top of the file, add the following:

<?php
if (!function_exists('custom_fatal_error')) {
    function custom_fatal_error() {
        $error = error_get_last();
        if (is_array($error)) {
            if ($error["type"] == E_ERROR) {
                echo file_get_contents("/www/500.html");
                die();
            }
        }
    }
}
register_shutdown_function('custom_fatal_error');

The above script will return the 500.html file anytime there is a fatal error detected.

This will handle the majority of issues, though error throwing can be pretty complex and may not always respond with this. For example to load your custom page during an exception error, you would add:

<?php
if (!function_exists('custom_exception')) {
    function custom_exception( Throwable $e )
    {
        echo file_get_contents("/www/500.html");
        die();
    }
}
set_exception_handler('custom_exception');

That's it! You now have custom fatal errors on your site. If you have suggestions for other ways to add error handling, feel free to leave a comment below.