Convert Errors to Exceptions in PHP

I was having a conversation with a buddy of mine the other day and we got on the topic of PHP not having a very standardized error system. Now that he’s working with Python the mix of errors and exceptions in PHP is an apparent shortcoming. PHP is funny like that, out of the box some times are just terrible, but they also give you the means to correct the situation so you can have the functionality as so desired.

To convert all of your errors into exceptions, you need to use the function set_error_handler() and define your own custom error handling function. Inside that function, just take the error message and throw the exception as you see fit:


function customErrorHandler($errno, $errstr, $errfile, $errline, array $errcontext)
	// Handles @ error suppression
	if (error_reporting === 0)
		return false

	throw new Exception($errstr, 0, $errno, $errfile, $errline

Really not much to it! Now when an error is encountered (and the @ suppression is not being used) the error will be thrown as an exception while retaining all of the pertinent information about the error.

It’s debatable whether or not this is a good practice or not, but it does provide you with a very consistent way to interact with PHP errors. Of course, if you wanted to you could add in additional logic to the error handler function, like say perhaps sending an email every time an error is encountered (because we always test our code and there should be no bugs in production, right? 😉

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

If you found this article helpful, please consider buying me a coffee.