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): boolmessage: The error message associated with the event (limited to 1024 characters).error_level: The type of error to trigger. This must be one of the predefined user-level error constants.
User-Level Error Constants
PHP provides specific constants to define the severity of the triggered error:
E_USER_NOTICE(Default): Used for non-critical, informational events. The script continues running normally.E_USER_WARNING: Used for non-fatal runtime issues. This indicates a potential problem, but script execution will not stop.E_USER_ERROR: Used for fatal runtime errors. This stops the execution of the script immediately, unless a custom error handler prevents it.E_USER_DEPRECATED: Used to warn that a specific feature or function is deprecated and should not be used in future versions.
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 executionCombining 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);