Alain Schlesser has written up a new post for his site sharing some of his suggestions for structuring your PHP exceptions including localization, catching them and using them with named constructors.
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. Your client will surely be thankful!
In this article, I want to talk about the way I currently set them up and use them in PHP, in the hopes to spark some discussion on the topic and get further feedback.
He starts with a few thoughts about why even using exceptions is a good idea (over just errors) and how to build on the included SPL exception set. He then gets into the suggestions about:
- naming conventions
- using named constructors to encapsulate logic
- working with localized exception messages
- catching exceptions
He ends the post by suggesting one last piece that can help make catching and handling exceptions easier - a centralized handler, something potentially like BooBoo from The PHP League.