Trigger Custom Errors and Warnings in PHP

This article explains how to use the native PHP trigger_error() function to generate custom user-level errors, warnings, and notices. You will learn how to configure different error levels, write practical implementation code, and understand how these triggered events integrate with PHP’s error-handling system to improve debugging and application control.

The trigger_error() Syntax

The trigger_error() function is used to trigger a user-defined error condition. It is highly useful when validating inputs, enforcing business logic, or flagging deprecated functions.

The syntax for the function is:

trigger_error(string $message, int $error_level = E_USER_NOTICE): bool

User-Level Error Constants

PHP provides specific constants to define the severity of the triggered error:

Practical Examples

1. Triggering a Custom Warning

Use E_USER_WARNING when a condition is met that does not break the entire application, but still requires developer attention.

function setAge($age) {
    if ($age < 0) {
        trigger_error("Age cannot be negative. Defaulting to 0.", E_USER_WARNING);
        $age = 0;
    }
    return $age;
}

$userAge = setAge(-5);

2. Triggering a Custom Fatal Error

Use E_USER_ERROR when a critical dependency or requirement is missing, requiring the script to stop executing.

function connectToDatabase($config) {
    if (empty($config['db_host'])) {
        trigger_error("Critical error: Database host is not defined.", E_USER_ERROR);
    }
    // Connection logic goes here
}

connectToDatabase([]); // This will stop script execution

Combining trigger_error() with a Custom Error Handler

By default, PHP handles these errors based on your error_reporting and display_errors settings in php.ini. You can intercept these triggered errors and format them using set_error_handler().

function myCustomHandler($errno, $errstr, $errfile, $errline) {
    echo "<b>[Error Level: $errno]</b>: $errstr in $errfile on line $errline<br>";
    
    if ($errno === E_USER_ERROR) {
        echo "Terminating application due to a fatal user error.";
        exit(1);
    }
}

// Set the custom handler
set_error_handler("myCustomHandler");

// Trigger a notice
trigger_error("This is a custom user notice.", E_USER_NOTICE);