When a PHP match expression has no default pattern defined, it throws an UnhandledMatchError. Consider, for example, the following:
// PHP 8+
$status = 600;
echo match ($status) {
200 => 'ok',
301, 302, 307, 308 => 'redirect',
400, 401 => 'bad request',
404 => 'not found',
500 => 'server error',
};
// Fatal error: Uncaught UnhandledMatchError
To throw a custom exception instead, you can do either of the following:
#Using default
Starting with of PHP 8, the throw keyword is an expression (as opposed to a statement, as in earlier versions of PHP, where it required to be on its own line). Therefore, you can simply throw the custom exception in the default pattern of the match expression, for example, like so:
// PHP 8+
$status = 600;
echo match ($status) {
200 => 'ok',
301, 302, 307, 308 => 'redirect',
400, 401 => 'bad request',
404 => 'not found',
500 => 'server error',
default => throw new InvalidStatusCodeException($status),
};
// Fatal error: Uncaught InvalidStatusCodeException
#Using try/catch
You can simply do the following:
- Wrap the
matchexpression in atry/catchblock; - Catch the
UnhandledMatchErrorerror, and; - Throw the custom exception in the
catchblock.
For example:
// PHP 8+
$status = 600;
try {
echo match ($status) {
200 => 'ok',
301, 302, 307, 308 => 'redirect',
400, 401 => 'bad request',
404 => 'not found',
500 => 'server error',
};
} catch (UnhandledMatchError $e) {
throw new InvalidStatusCodeException($status);
}
// Fatal error: Uncaught InvalidStatusCodeException