wraugh/defphp

Dynamic exceptions for PHP

0.3.0 2018-04-08 13:33 UTC

This package is not auto-updated.

Last update: 2024-09-24 06:59:00 UTC


README

This library allows you to throw well-typed exceptions without having to maintain a hierarchy of boilerplate exception class definitions.

Usage

Install it with composer: $ composer require wraugh/defphp.

Then throw exceptions by calling the static ex method:

try {
    \Defphp\Defphp::ex('MyException', "Hello, world");
} catch (MyException $e) {
    error_log($e->getMessage()); // logs "Hello, world"
}

You can give your exceptions multiple types by using an array or a comma-separated string:

try {
    \Defphp\Defphp::ex('DbError,NotFound');
} catch (NotFound $e) {
    http_response_code(404);
}

You can also export the ex method as a function in the global namespace:

\Defphp\Defphp::alias();
ex('MyEx'); // throws an exception of type MyEx

// You can specify your own alias name
\Defphp\Defphp::alias('ohno');
ohno('MyEx'); // also throws an exception of type MyEx

Or you can add an ex static method to your class by using the Ex trait:

class MyClass {
    use \Defphp\Ex;

    public function __construct($foo) {
        if ($foo == 'bar') {
            static::ex("Foobar", '$foo is bar');
        }
    }
}

The ex method supports the same arguments as the constructor to the base Exception class:

try {
    throw new MyException("message", 42);
} catch (MyException $e) {
    // rethrow an equivalent exception
    \Defphp\Defphp::ex('MyException', "message", 42, $e);
}

Caveats

Defphp will push one or two lines onto the stack trace of exceptions. All exceptions thrown via Defphp will appear to have been thrown from the same line in the code: the line in Defphp::ex that is actually a throw statement. The logical source of the exception (where the ex method was called) will therefore be one or two lines below in the stack trace.

Defphp defines interfaces in the global namespace. If one of your Defphp exception types conflicts with one of your interfaces, you're going to have a bad time. This is easily avoided: large projects typically define everything inside their own namespace, and global names are easy to keep track of in small projects.

Making a typo in an exception type will still result in an exception being thrown (as opposed to stock PHP which will fire a "class not found" fatal error). This can make it harder to find such typos. See the notes.md file for further discussion of this.