一些常规的PHP框架都会对PHP的错误、异常进行异常处理封装,方便框架日志记录,开发的时候方便处理。我们先看看几个框架错误处理:
Laravel
Laravel在app初始化的时候注册了错误处理函数,异常处理函数,异常退出处理函数,最终将错误转化成异常抛出,统一通过异常处理函数进行处理。
public function bootstrap(Application $app)
{
$this->app = $app;
error_reporting(-1);
set_error_handler([$this, 'handleError']);
set_exception_handler([$this, 'handleException']);
register_shutdown_function([$this, 'handleShutdown']);
if (! $app->environment('testing')) {
ini_set('display_errors', 'Off');
}
}
public function handleError($level, $message, $file = '', $line = 0, $context = [])
{
if (error_reporting() & $level) {
throw new ErrorException($message, 0, $level, $file, $line);
}
}
public function handleShutdown()
{
if (! is_null($error = error_get_last()) && $this->isFatal($error['type'])) {
$this->handleException($this->fatalExceptionFromError($error, 0));
}
}