Working with Exceptions

You already may use PHP built-in exceptions or you might also have already build your own exceptions for your app, like for instance MyException which implements Throwable interface.

Of course, you can still use the traditional way throw \MyException() but you also can use Fault::throw() or Fault::exception() methods and get all the benefits of Fault Manager like Custom Exceptions and Event Stream.

Example 4 Using Fault Manager
try {
    try {
        try {
            // Using Fault::throw()
            Fault::throw(\Exception::class, 'Bad message');
        } catch (\Exception $exception) {
            // Some logic after catching \Exception
            // Let's throw one of our own now with Fault::exception()
            throw Fault::exception(\MyException::class, 'More info');
        }
    } catch (\MyException $exception) {
        // Some logic goes here...
        // Why not throw an already defined namespaced exception?
        // Let's do it with Fault::throw()
        Fault::throw(\MyApp\MyException::class, 'Too many exceptions!');
    }
} catch (\MyApp\MyException::class $exception) {
    // Some more logic here...
} finally {
    // No more logic left! :D
}

Note

Fault::throw() is an alias to Fault::exception() with a difference that Fault::exception() returns the exception and Fault::throw() throws it directly. As you can see in the Fault class on line 146

Example 5 /Fault.php
145
146
147
148
149
150
151
152
153
154
    public static function throw(
        string $exceptionClass,
        string $message = '',
        int $code = 0,
        ?\Throwable $previous = null,
        array $arguments = []
    ): void {
        throw self::exception($exceptionClass, $message, $code, $previous, $arguments);
    }
}

Message Arguments

As you may noticed, Fault::exception() as also Fault::throw() receive 5 parameters:

Parameters
  • $exceptionClass (string)

  • $message (string)

  • $code (int)

  • $previous (null | \Throwable <Throwable>)

  • $arguments (array)

  • $exceptionClass The name of the Exception class we want to throw

  • $message The message we want to deliver

  • $code The error code

  • $previous Previous Exception object

  • $arguments Array of items to replace in message text. See vsprintf

Since the first 4 parameters are self-explanatory we will focus on 5 th param $arguments, a simple example:

Example 6 Message with arguments
Fault::throw(\Exception::class, 'Goodbye %s!', 0, null, ['world']);

The above example will produce a Fatal error: Uncaught Exception: Goodbye world!

As you probably realised already, is not very convenient to have $arguments param at the end, but at least for time being, is better to not break the semantics of PHP’s Exception::__construct.

class Exception
public __construct([string $message = ""[, int $code = 0[, Throwable $previous = NULL]]])