Event Handler
Taking into consideration that we have Event Stream enabled, that means that each exception thrown in our app is an event.
So that:
Fault::throw(\Exception::class, 'bad message');
Is an event called ‘Exception’.
In order to register a handler we use the Fault::registerHandler()
method which takes 3 parameters:
-
class
Fault
-
public static
registerHandler
($eventId, $handler, $override=false) - Parameters
$eventId (string)
$handler (\Omega\FaultManager\Interfaces\FaultManagerEventHandler)
$override (bool)
-
public static
$eventId
The name of the event$handler
The handler object that must implement the FaultManagerEventHandler interface$override
If that is set to true, then it will override a handler previously defined
Fault::registerHandler(\Exception::class, MyHandler());
If the asterisk (*) character is used as a value for $eventId
parameter, then that handler will listen to
all events.
-
class
Fault
-
ALL_EVENTS = *
- Type
string
-
Fault::registerHandler(Fault::ALL_EVENTS, MyHandler());
Event Handler Object
The event handler object must implement the \Omega\FaultManager\Interfaces\FaultManagerEventHandler
interface.
a simple event handler will look like this:
class SimpleHandler implements \Omega\FaultManager\Interfaces\FaultManagerEventHandler
{
public function __invoke(\Throwable $exception)
{
\dump('I got: ' . \get_class($exception) . " with message: '{$exception->getMessage()}'");
}
}
the following code:
Fault::registerHandler(Fault::ALL_EVENTS, new SimpleHandler());
try {
try {
Fault::throw('CustomException', 'Message from try!');
} catch (\CustomException $exception) {
Fault::throw(\Exception::class, 'Message from catch!');
}
} catch (\Exception $exception) {
\dump('I catch ' . get_class($exception) . '!');
}
will result in:
"I got: CustomException with message: 'Message from try!'"
"I got: Exception with message: 'Message from catch!'"
"I catch Exception!"