/**
* Bootstrap the given application.
*
* @param \Illuminate\Contracts\Foundation\Application $app
* @return void
*/
public function bootstrap(Application $app)
{
$this->app = $app;
# 报告所有php错误
error_reporting(-1);
# 定义错误发生时处理动作
set_error_handler([$this, 'handleError']);
# 用户抛出异常时处理动作(用作没使用try/catch块时)
set_exception_handler([$this, 'handleException']);
# 程序执行超时、程序被用户强制停止时、PHP代码执行完成时 被调用执行
register_shutdown_function([$this, 'handleShutdown']);
if (! $app->environment('testing')) {
ini_set('display_errors', 'Off');
}
}
/**
* Convert PHP errors to ErrorException instances.
*
* @param int $level # 错误的级别
* @param string $message # 错误信息
* @param string $file # 发生错误的文件名
* @param int $line # 发生错误的行号
* @param array $context # 发生错误时的上下文(变量作用域)
* @return void
*
* @throws \ErrorException
*/
public function handleError($level, $message, $file = '', $line = 0, $context = [])
{
# error_reporting() 返回当前的错误报告级别 判断是否一致
if (error_reporting() & $level) {
# 抛出一个PHP内置的错误异常
throw new ErrorException($message, 0, $level, $file, $line);
}
}
/**
* Handle an uncaught exception from the application.
*
* Note: Most exceptions can be handled via the try / catch block in
* the HTTP and Console kernels. But, fatal error exceptions must
* be handled differently since they are not normal exceptions.
*
* @param \Throwable $e # 抛出的异常对象
* @return void
*/
public function handleException($e)
{
# 如果当前抛出异常不是Exception的实例
if (! $e instanceof Exception) {
# 封装一个自定义的错误异常返回
$e = new FatalThrowableError($e);
}
try {
# 异常被传递给指定的report() 方法 最终被分发给App/Exception/Handler.php的基类Hander中report()方法被处理 更多参考手册 - 错误与日志
$this->getExceptionHandler()->report($e);
} catch (Exception $e) {
//
}
# 判断当前环境是否运行在控制台
if ($this->app->runningInConsole()) {
$this->renderForConsole($e);
} else {
# 调用render方法响应一个HTTP请求
$this->renderHttpResponse($e);
}
}
/**
* Report or log an exception.
*
* @param \Exception $e
* @return void
*
* @throws \Exception
* 参考手册 - 处理dontReport属性包含的是否会被记录的异常类型数组
*/
public function report(Exception $e)
{
# 如果当前异常存在 dontReport 属性中不会被记录到日志中去
if ($this->shouldntReport($e)) {
return;
}
# 日志记录 记录抛出异常到日志中
try {
$logger = $this->container->make(LoggerInterface::class);
} catch (Exception $ex) {
throw $e; // throw the original exception
}
$logger->error($e);
}
/**
* Handle the PHP shutdown event.
*
* @return void
*/
public function handleShutdown()
{
# error_get_last()获取最后发生的错误
if (! is_null($error = error_get_last()) && $this->isFatal($error['type'])) {
$this->handleException($this->fatalExceptionFromError($error, 0));
}
}
网友评论