我正在努力确保全局处理从数据库连接问题引发的异常。
我在render()方法的app / Exceptions \ Handler.php中添加了以下内容,但是没有捕到任何异常:
<?php
namespace App\Exceptions;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use PDOException;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
if ($e instanceof AuthorizationException) {
return response()->json((['status' => 403, 'message' => 'Insufficient privileges to perform this action']), 403);
}
if ($e instanceof MethodNotAllowedHttpException) {
return response()->json((['status' => 405, 'message' => 'Method Not Allowed']), 405);
}
if ($e instanceof NotFoundHttpException) {
return response()->json((['status' => 404, 'message' => 'The requested resource was not found']), 404);
}
if ($e instanceof QueryException) {
return response()->json((['id' => 0, 'status_billing' => 'The requested resource was not found']), 500);
}
if ($e instanceof PDOException) {
return response()->json((['id' => 0, 'status_billing' => 'The requested resource was not found']), 500);
}
return parent::render($request, $e);
}
}
这也被添加到我的app.php:
$app->singleton( App\Exceptions\Handler::class );
对于我的生活,我无法让它发挥作用。
非常感谢任何帮助/建议
由于
答案 0 :(得分:3)
从app.php更改以下行
$app->singleton( App\Exceptions\Handler::class );
为:
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
修改强>
在上述异常处理程序绑定中需要接口的原因是,当处理Route时抛出异常时,将调用以下函数来处理该异常。
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);
return $handler->render($passable, $e);
}
if条件检查容器是否具有ExceptionHandler类的绑定。如果存在绑定,则异常将被传递到该异常处理程序类以进一步处理。如果没有声明绑定,则将重新抛出异常。这里检查绑定Illuminate\Contracts\Debug\ExceptionHandler
。这就是为什么当你使用App\Exceptions\Handler::class
直接绑定时,异常处理程序不会捕获异常。