Neat exception classes with traits

So we’re all told that our exception messages should be nice and informative and often sprintf is used to format the exception messages. This is all well and good and is very helpful when an exception gets thrown. However it leads to code that looks like this:

Now this looks like a bit of a mess to me, it takes up 9 lines and has 3 extra levels of indentation.

Some time ago I submitted a pull request on a project (I forget which) and Ocramius suggested that I use a static factory method inside my exception to make it neater, I had a look at some of the exception class and definitely found it was neater (I assume others are out there using this pattern too?).

I decided to adopt this pattern and instead of the code above I now had this:

Exception Class


So far this has certainly tidied up the code throwing the exception and made it much easier to see what’s going on. Also all the exception messages are in 1 place (inside the exception class) so they’re easier to manage.

However the exception class itself still looks a bit messy and I thought could use some improvement. With the wonders of PHP 5.4’s nice new traits I created the following trait:

So now by telling my exception class to use this trait and I can have nice neat exception classes like so:


That now I think is a much more elegant solution.

Please let me know of any thoughts or suggestions!

Leave a Reply

Your email address will not be published. Required fields are marked *