PHP Set Exception Handler

Summary: in this tutorial, you will learn how to set an exception handler using the PHP set_exception_handler() function.

Introduction to the PHP set_exception_handler function

In practice, it’s very difficult to catch every possible exception. If an exception is uncaught, you’ll see the exception message on the page.

PHP allows you to catch the uncaught exceptions by registering a global exception handler.

The global exception handler allows you to show a user-friendly message to the users while logging the important information into a log file for troubleshooting later.

To register a global exception handler, you use the set_exception_handler() function.

The set_exception_handler() function accepts a callable where you can place the code to handle the uncaught exceptions. For example:

<?php

set_exception_handler(function ($ex) {
	// handle the uncaught exception
});Code language: HTML, XML (xml)

To use a global function, you can pass the function name to the set_exception_handler() function like this:

<?php 

set_exception_handler('handle_exceptions');Code language: HTML, XML (xml)

In case you want to use a method of an object, you need to pass an array with the first element is the object and the second element is the method name. For example:

class ExceptionHandler
{
	public function handle(Exception $ex)
	{
		// code to handle the exception
	}
}

$handler = new ExceptionHandler();

set_exception_handler([$handler, 'handle']);Code language: PHP (php)

Note that method of the object must be public to be used an exception handler.

Similary, you can use a public static method of a class as the exception handler:

<?php

class ExceptionHandler
{
	public static function handle(Exception $ex)
	{
		// code to handle the exception
		// ...
	}
}

set_exception_handler(['ExceptionHandler', 'handle']);Code language: HTML, XML (xml)

PHP set_exception_handler example

First, create the following directory structure with the corresponding files like this:

.
├── bootstrap.php
├── index.php
└── logs
    └── errors.logCode language: plaintext (plaintext)
FilenameDirectoryDescription
bootstrap.php.contains the code for bootstrapping the application
index.php.is the entry page of the application
errors.loglogscontains the logging information

Second, add the following code to the bootstrap.php file:

<?php

set_exception_handler(function (Exception $ex) {
	// set default timezone
	date_default_timezone_set('America/Los_Angeles');

	// get the current date & time
	$time = date('F j, Y, g:i a e O');

	// format the exception message
	$message = "[{$time}] {$ex->getMessage()}\n";

	// append to the error log
	error_log($message, 3, 'logs/errors.log');

	// show a user-friendly message
	echo 'Whoops, looks like something went wrong!';
});

Code language: HTML, XML (xml)

In the bootstrap.php file, we set the default time zone to 'America/Los_Angeles', get the current date and time, format the exception message, and log it into the errors.log file located in the logs directory.

The second argument (3) of the error_log() function indicates that it will append the log entry in the errors.log file.

Third, place the following code in the index.php file:

<?php

require 'bootstrap.php';

function add($a, $b)
{
	if (!is_numeric($a) || !is_numeric($a)) {
		throw new InvalidArgumentException('Both arguments must be numeric or numeric strings');
	}

	return $a + $b;
}

echo add('Hi', 'there');
Code language: HTML, XML (xml)

The index.php includes the bootstrap.php file. And it defines a function called add() that returns the sum of two numbers.

However, the function call add('Hi', 'there') uses string arguments instead of numbers. Therefore, it’ll throw an exception InvalidArgumentException.

Since this exception is not caught in the index.php, the global exception handler will catch it. The index.php will show the following message:

Whoops, looks like something went wrong!Code language: plaintext (plaintext)

If you look at the errors.log file, you’ll find something like:

[April 10, 2021, 8:35 pm America/Los_Angeles -0700] File: ...\index.php, Line: 8, Message: Both arguments must be numeric or numeric stringsCode language: plaintext (plaintext)

Summary

  • Use the set_exception_handler() function to register a global exception handler that handles uncaught exceptions.
Did you find this tutorial useful?