gpt4 book ai didi

php - 有没有一种干净的方法来拦截Laravel中的* handled *错误?

转载 作者:行者123 更新时间:2023-12-03 08:45:16 34 4
gpt4 key购买 nike

我试图拦截laravel中的错误,我发现了一个很好的方法:

Simulating a error:


public function index(){       

$users = User::all(); //<-SQL exeception here

return response()->json(['message'=>'ok'], 200);
}

app/Exceptions/Handler.php


public function report(Exception $exception)
{
dd($exception); //<-intercept my error here
parent::report($exception);
}

工作得很好,我可以做任何我想做的错误,但是当我使用try-catch块时,我的拦截器不起作用:

Simulating error again


public function index(){

try {

$users = User::all();//<-SQL exeception here

} catch (\Throwable $th) {

error_log('Error handled');

//MyInterceptor::manuallyIntercept($th);

}

return response()->json(['message'=>'ok'], 200);
}

有没有一种干净的方法以编程方式拦截所有已处理的错误?

最佳答案

不是报告方法,您需要在Handler.php上使用render方法
您将看到$this->errorResponse,它将仅返回JSON响应。我只想展示主要思想。

public function render($request, Exception $exception)
{
if ($exception instanceof ValidationException) {
return $this->convertValidationExceptionToResponse($exception, $request);
}
if ($exception instanceof ModelNotFoundException) {
$modelName = strtolower(class_basename($exception->getModel()));
return $this->errorResponse("Does not exists any {$modelName} with the specified identificator", 404);
}
if ($exception instanceof AuthenticationException) {
return $this->unauthenticated($request, $exception);
}
if ($exception instanceof AuthorizationException) {
return $this->errorResponse($exception->getMessage(), 403);
}
if ($exception instanceof MethodNotAllowedHttpException) {
return $this->errorResponse('The specified method for the request is invalid', 405);
}
if ($exception instanceof NotFoundHttpException) {
return $this->errorResponse('The specified URL cannot be found', 404);
}
if ($exception instanceof HttpException) {
return $this->errorResponse($exception->getMessage(), $exception->getStatusCode());
}
if ($exception instanceof QueryException) {
$errorCode = $exception->errorInfo[1];
if ($errorCode == 1451) {
return $this->errorResponse('Cannot remove this resource permanently. It is related with any other resource', 409);
}
}
if (config('app.debug')) {
return parent::render($request, $exception);
}
return $this->errorResponse('Unexpected Exception. Try later', 500);
}

错误响应方法
protected function errorResponse($message, $code)
{
return response()->json(['error' => $message, 'code' => $code], $code);
}

关于php - 有没有一种干净的方法来拦截Laravel中的* handled *错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56222781/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com