-
Notifications
You must be signed in to change notification settings - Fork 0
Usage: SPL Faults and Exceptables
Adrian edited this page Aug 10, 2025
·
1 revision
Faults and Exceptable classes based on each of PHP's built-in SPL exceptions are provided. These provide convenient base classes to build your own Exceptables from that can also be handled in an exceptable-agnostic way.
For more information about SPL Exceptions, see the php manual or this pretty decent (if dated) WebDevEtc article.
The Spl Exceptables extend from the built-in Spl Exceptions, and so can be caught using their corresponding Spl Exception class. Each Spl Exceptable also has a default error code for generic use, and so in a pinch can be used "out-of-the-box."
<?php
use at\exceptable\Spl\SplFault;
throw (SplFault::RuntimeError)();
// throws:
// at\exceptable\Spl\RuntimeException<SplFault::RuntimeError>...meanwhile
<?php
// note, this is php's built-in SPL type, not the exceptable type
use RuntimeException;
try {
require "that-file.php";
} catch (RuntimeException $e) {
echo $e->getMessage();
// prints:
// at\exceptable\Spl\RuntimeException: at\exceptable\Spl\SplFault.RuntimeError
}The better approach is to use Spl exceptables as base classes for your application's own Exception types, with your own Fault cases.
<?php
use at\exceptable\ {
Spl\InvalidArgumentException,
Spl\LogicException
};
enum AdventureFault implements Fault {
use IsFault;
case Bogus;
case MostBogus;
// you can change what exceptable type your faults are thrown as
protected function exceptableType() : string {
return match ($this) {
self::Bogus => InvalidArgumentException::class,
self::MostBogus => LogicException::class
};
}
}
throw (AdventureFault::Bogus)();
// throws:
// at\exceptable\Spl\InvalidArgumentException<AdventureFault::Bogus>
throw (AdventureFault::MostBogus)();
// throws:
// at\exceptable\Spl\LogicException<AdventureFault::MostBogus>