Monitoring Uncaught PHP Errors in WordPress

Monitoring Uncaught PHP Errors in WordPress

While the official AlertHub WordPress plugin allows you to monitor standard WordPress hooks easily, some errors are “uncontrolled” — they crash the script before any standard action runs. These are often Fatal Errors (500 Internal Server Error).

To monitor these, we need to go a bit deeper. Since AlertHub exposes a public API method AlertHub_API::send_alert, we can use it within a shutdown function in your theme’s functions.php or a site-specific plugin.

The Code Snippet

Add the following code to your theme’s functions.php. It registers a shutdown function that checks if the script ended due to a fatal error.

function alerthub_fatal_error_handler() {
    $error = error_get_last();
    
    // Check if it's a fatal error type
    if ( $error && in_array( $error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR] ) ) {
        
        // Ensure AlertHub is active and available
        if ( class_exists( 'AlertHub_API' ) ) {
            $title = 'Critical Site Error';
            $message = "Error: {$error['message']}\nFile: {$error['file']}\nLine: {$error['line']}";
            
            // Send the alert immediately
            AlertHub_API::send_alert( 
                'fatal_error', 
                $title, 
                $message, 
                'error' 
            );
        }
    }
}
register_shutdown_function( 'alerthub_fatal_error_handler' );

How It Works

  1. register_shutdown_function: This ensures our code runs even if the script crashes.
  2. error_get_last: Retrieves the error that caused the crash.
  3. class_exists('AlertHub_API'): We make sure AlertHub is loaded so we can reuse its configuration (Project Key) and logic.
  4. AlertHub_API::send_alert: We send the alert using the standard plugin method.

Test Properly!

To test this, you can (temporarily!) add a syntax error or a call_to_undefined_function() in a test page. Do not do this on a production site without backups.

With this setup, you’ll be the first to know if a plugin update or a code change brings your site down.