Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer. You can expect quick tips, links to interesting tutorials, opinions and packages. Want to learn the cool stuff? Then sign up now!

Structuring PHP exceptions

Alain Schlesser wrote an article on how to manage exceptions in a large codebase.

I seem to constantly work on improving my habits regarding the use of exceptions. I think it is an area that I haven’t yet fully explored, and it is very difficult to find anything more than very basic explanations and tutorials online. While the consensus is to use exceptions, there is very little information on how to structure and manage them in a larger codebase. The larger and more complex your projects become, the more important it is to start with a proper structure to avoid expensive refactoring later on.


In my opinion a good exception message in most cases contains three things:

  • the reason why something went wrong
  • the data that caused the problem
  • suggestions on how to solve the problem

Named constructors for exceptions are the perfect place to build up such a message. Want to learn more? Ross Tuck wrote a good blog post on the subject too.

Freek Van der Herten is a partner and developer at Spatie, an Antwerp based company that specializes in creating web apps with Laravel. After hours he writes about modern PHP and Laravel on this blog. When not coding he’s probably rehearsing with his kraut rock band. He loves waffles and butterflies.