Create your own Exception Handler in PHP

If you’re used to writing your own PHP applications, you will no doubt be used to having to deal with exceptions being thrown at awkward moments. Resulting in a ugly 500 error being shown to the user and no extra direct from them to take.

Luckily we can choose our own way of handling these exceptions, showing a better message or logging the error more efficiently. In an ideal world, we wouldn’t need these as everything would work perfectly, all the time – but alas we need to prepare for the inevitable. Even if the exception has been caused by an external service.

One solution to this problem would be to wrap everything in a try-catch statement, which should be done on individual code blocks because it will allow you to act differently to each scenario. Our exception handler is just being used as a catch all last resort mechanism.

As a Function#

<?php

ob_start();

function exceptionHandler($exception) {

	// Clears any echo'd data which has already been shown
	// More info: http://bit.ly/1FPGsU4
	ob_end_clean();

	// Show a human message to the user.
	echo '<h1>Server error (500)</h1>';
	echo '<p>Please contact your administrator, etc.</p>';

	// Save a copy for the sys-admins ;)
	error_log($exception->message);
}

set_exception_handler('exceptionHandler');

As you can see it’s only a small section of code, relying heavily on the set_exception_handler function. We do also make use of the ob_start() and ob_end_clean() functions to clear and data printed to the screen – just in case it has sensitive data in it, and to keep our error page looking nice.

To test it out, you can just use the snippet below to throw an exception.

// Not needed, just shows the exception handler works!
throw new Exception();

As a Class#

<?php

namespace ErrorHandling;

ob_start();

class ExceptionHandler {

public function __construct() {
set_exception_handler(array($this, 'fire'));
}

public function fire($exception) {

// Clears any echo'd data which has already been shown
// More info: http://bit.ly/1FPGsU4
ob_end_clean();

// Show a human message to the user.
echo '<h1>Server error (500)</h1>';
echo '<p>Please contact your administrator, etc.';

// Save a copy for the sys-admins ;)
error_log($exception->getMessage());
}

}

// Construct & Initialize our ExceptionHandler
// within a different namespace: new \ErrorHandling\ExceptionHandler();
new ExceptionHandler();

The only real difference with this wrapped up as a class is that we have moved the set_exception_handler function into the constructor of the class, so that it gets set once we create our ExceptionHandler object. We have also namespaced our class as ErrorHandling, so if you’re calling this from a different namespace you can call it in full with \ErrorHandling\ExceptionHandler.