What is Exception severity in PHP?

php error-handling

521 观看

1回复

51 作者的声誉

I saw this code in the PHP documentation:

try {
throw new ErrorException("Exception message", 0, E_USER_ERROR);
} catch(ErrorException $e) {
echo "This exception severity is: " . $e->getSeverity();
var_dump($e->getSeverity() === E_USER_ERROR);
}

And it continues:

This exception severity is: 256
bool(true)

What does exception severity mean, and do I have to use it at all?

作者: Michael Akinlaby 的来源 发布者: 2017 年 9 月 15 日

回应 1


2

8216 作者的声誉

The $severity is an integer representing, well, the severity of the error thrown. The manual states that it can be any integer, but it's preferable to use a constant from the predefined error constants. These are the same used by error_reporting.

Notice that ErrorException extends Exception, adding the $severity parameter. This is because ErrorException is normally used to convert the normal errors PHP shows into Exceptions. This is done via set_error_handler().

So, the ErrorException::$severity is really the severity of the PHP error that would have been shown if you hadn't thrown it as an Exception. You can use it to decide what to do when you catch an ErrorException depending on what caused it.

作者: ishegg 发布者: 2017 年 9 月 15 日
32x32