in PHP

Formatting Exception Messages

I read this blog posts back in 2015 and I still use this techinque on my own projects, I find it a great way of creating readable exception messages on large projects using domain based exceptions.

Please read Ross Tuck blog post on Formatting Exception Messages.

The general idea is when creating custom exceptions you will normally have multiple classes per exception.

Instead of having classes for each type of exception

class InvalidNumberGreaterThan extends \Exception
{
}

class InvalidNumberLessThan extends \Exception
{
}

You move these into a single domain exception InvalidNumberRange and move both exceptions into one.

class InvalidNumberRange extends \Exception
{
    public static function numberGreaterThan($number)
    {
        return new static("Number ($number) must be greater than 10");
    }

    public static function numberLessThan($number)
    {
        return new static("Number ($number) must be less than 20");
    }
}

Now these can be thrown by using

throw InvalidNumberRange::numberGreaterThan($number);
throw InvalidNumberRange::numberLessThan($number);

Please read Ross Tuck blog post on Formatting Exception Messages.

Subscribe To The Weekly Newsletter

Get weekly updates to your email