PHP Error Handling

Beginner
8 min read
Updated: Nov 2026
3 examples
Report, handle & log

Definition and Usage

Error handling in PHP is how your script reports, logs, and reacts to problems such as warnings, notices, deprecations, and fatal errors. PHP ships a small set of functions that let you choose which levels to report, raise your own errors, run custom handler code, and inspect what went wrong.

Use error_reporting() to pick which levels matter, and trigger_error() (alias user_error()) to raise a user-level error. Send those errors to your own callback with set_error_handler(), then undo it with restore_error_handler().

After something fails, error_get_last() returns the last error array and error_clear_last() resets it. Write messages to a log with error_log(), look at the call stack with debug_backtrace(), and catch anything left uncaught with set_exception_handler().

This page explains the ideas. The Error Functions index lists all 14 function guides.

Report in development, log in production.

Use error_reporting(E_ALL) while you build. In production, keep log_errors on and display_errors off so visitors never see file paths or stack details.

Errors are not exceptions.

Warnings and notices go through set_error_handler(). Objects you throw go through try and catch. See PHP Exception for that side, or convert errors into ErrorException inside your handler.

PHP Syntax

The usual report, raise, handle, and inspect pattern:

PHP
error_reporting(E_ALL);                 // choose which levels to report

trigger_error("Low disk space", E_USER_WARNING);   // raise a user error
user_error("Same thing", E_USER_NOTICE);           // alias of trigger_error()

set_error_handler(function ($errno, $errstr, $file, $line) {
    error_log("[$errno] $errstr in $file:$line");  // write to the log
    return true;                                   // true = handled
});
restore_error_handler();                // go back to the previous handler

$last = error_get_last();               // array or null
error_clear_last();                     // reset it

$frames = debug_backtrace();            // call stack as array
set_exception_handler(function (Throwable $e) {
    echo "Uncaught: ", $e->getMessage();
});

Core Ideas

What to remember when you work with errors in PHP:

IdeaFunctionRemember
Levelserror_reporting()Chooses which levels PHP reports; E_ALL covers everything
Raisetrigger_error() / user_error()Use E_USER_* levels; user_error() is an alias
Handleset_error_handler()Your callback receives level, message, file, and line
Undorestore_error_handler()Pops back to the previous handler
Last errorerror_get_last() / error_clear_last()Array with type, message, file, line, or null
Logerror_log()Sends a message to the server log, a file, or email
Stackdebug_backtrace()Frame 0 is the current call; later frames are callers
Uncaught exceptionsset_exception_handler()Runs only when an exception is not caught anywhere

PHP Examples

Three short scripts that show how error handling works in PHP. Replace the messages with your own.

Example 1 — Custom error handler

Raise a user error with trigger_error() and catch it with your own set_error_handler() callback.

PHP
<?php
error_reporting(E_ALL);

set_error_handler(function (int $errno, string $errstr): bool {
    echo "Handled [$errno]: $errstr", PHP_EOL;
    return true;
});

trigger_error("Low disk space", E_USER_WARNING);

restore_error_handler();
echo "Handler restored", PHP_EOL;
?>

How It Works

  1. set_error_handler() registers a callback for non-fatal errors.
  2. trigger_error() raises E_USER_WARNING, which equals 512, and PHP calls your callback instead of printing.
  3. restore_error_handler() removes your callback and brings back the previous one.

Example 2 — Read the last error

Suppress a warning with @, read it with error_get_last(), then reset it with error_clear_last().

PHP
<?php
$data = @file_get_contents("missing.txt");

$err = error_get_last();
echo $err['type'] === E_WARNING ? "E_WARNING" : "other", PHP_EOL;
echo $err['message'], PHP_EOL;

error_clear_last();
var_dump(error_get_last());
?>

How It Works

  1. The @ operator hides the warning, but PHP still records it.
  2. error_get_last() returns an array with type, message, file, and line.
  3. error_clear_last() resets the record, so the next call returns NULL.

Example 3 — Backtrace and exception handler

Use debug_backtrace() to find the caller, then let set_exception_handler() catch an uncaught exception.

PHP
<?php
function logCaller(): void
{
    $frames = debug_backtrace();
    echo $frames[1]['function'], PHP_EOL;
}

function save(): void
{
    logCaller();
}

save();

set_exception_handler(function (Throwable $e): void {
    echo "Uncaught: ", $e->getMessage(), PHP_EOL;
});

throw new RuntimeException("Unexpected failure");
?>

How It Works

  1. debug_backtrace() returns frame 0 for logCaller() and frame 1 for its caller, save().
  2. set_exception_handler() registers a callback for exceptions that no catch block handles.
  3. The RuntimeException is uncaught, so your handler prints the message and the script ends.

Next: PHP Error Functions Index

After you know levels, handlers, and the last error, open the functions index for all 14 guides.

Start withWhy
error_reporting()Choose which error levels PHP reports
trigger_error()Raise your own user-level errors
set_error_handler()Route errors to your own callback
error_log()Write messages to a log file or the server log
debug_backtrace()Inspect the call stack as an array
set_exception_handler()Handle exceptions that nothing else caught

Full list: PHP Error Functions index (/php/error/function).

Frequently Asked Questions

Error handling is how your script reports, logs, and reacts to problems such as warnings, notices, and fatal errors. PHP gives you functions to choose which levels to show, raise your own errors, run custom handler code, and read the last error that happened.
Classic PHP errors (warnings, notices, deprecations) are reported through the error system and handled with set_error_handler(). Exceptions are objects you throw and catch with try and catch. A handler can convert an error into an ErrorException if you want one style of handling.
Call error_reporting(E_ALL) to report every level while developing. In production, keep logging on and display off. error_reporting() only chooses which levels PHP cares about; display_errors and log_errors control where messages go.
None. user_error() is an alias of trigger_error(). Both raise a user-level error such as E_USER_WARNING or E_USER_NOTICE, which your set_error_handler() callback can catch.
Use it right after an operation that may fail quietly, especially when you suppress the message with the @ operator. It returns an array with type, message, file, and line, or null if no error happened. Call error_clear_last() to reset it.
Practice the examples here, then open the Error Functions index for all 14 function guides, from error_reporting() and set_error_handler() to debug_backtrace() and set_exception_handler().

Browse every Error function

Open the functions index for categorized guides with examples and FAQs.

Error Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful