框架初始化时,在最外层设置 try catch,便于捕捉异常。
protected function prepareDestination(Closure $destination)
{
return function ($passable) use ($destination) {
try {
return $destination($passable);
} catch (Exception $e) {
return $this->handleException($passable, $e);
} catch (Throwable $e) {
return $this->handleException($passable, new FatalThrowableError($e));
}
};
}
捕捉到异常
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
protected function handleException($passable, Exception $e)
{
if (! $this->container->bound(ExceptionHandler::class) ||
! $passable instanceof Request) {
throw $e;
}
$handler = $this->container->make(ExceptionHandler::class);
$handler->report($e);
$response = $handler->render($passable, $e);
if (method_exists($response, 'withException')) {
$response->withException($e);
}
return $response;
}
进到AppExceptionsHandler::class的report方法
public function report(Exception $e)
{
if ($this->shouldntReport($e)) {
return;
}
if (method_exists($e, 'report')) {
return $e->report();
}
try {
$logger = $this->container->make(LoggerInterface::class);
} catch (Exception $ex) {
throw $e; // throw the original exception
}
$logger->error(
$e->getMessage(),
array_merge($this->context(), ['exception' => $e]
));
}
registerCoreContainerAliases() 设置了LoggerInterface::class的别名为log,查看AppServiceProvider文件
app()->instance('log', new \Illuminate\Log\Writer(
$this, app()['events']
));
trace链
在每层的HEADER里定义了HTTP_X_TRACE_ID