Есть ли чистый способ перехвата * обработанных * ошибок в Laravel? - PullRequest
0 голосов
/ 20 мая 2019

Я пытаюсь перехватить ошибки в laravel, и я нашел хороший способ сделать это:

Имитация ошибки:

public function index(){       

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

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

приложение / исключения / handler.php

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

Работает очень хорошо, и я могу делать все, что захочу с ошибкой, но когда я использую блок try-catch, мой перехватчик не работает:

Имитация ошибки снова

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);
}

Существует ли чистый способ программного перехвата всех обработанных ошибок?

1 Ответ

0 голосов
/ 21 мая 2019

Не метод отчета, вам нужно использовать метод рендеринга на Handler.php Вы увидите $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);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...