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.