Laravel API, how to properly handle errors

后端 未结 6 1030
后悔当初
后悔当初 2021-01-30 15:16

Anyone know what is the best way to handle errors in Laravel, there is any rules or something to follow ?

Currently i\'m doing this :

public function st         


        
6条回答
  •  忘了有多久
    2021-01-30 15:44

    Using some code from @RKJ best answer I have handled the errors in this way:

    Open "Illuminate\Foundation\Exceptions\Handler" class and search for a method named "convertExceptionToArray". This method converts the HTTP exception into an array to be shown as a response. In this method, I have just tweaked a small piece of code that will not affect loose coupling.

    So replace convertExceptionToArray method with this one

    protected function convertExceptionToArray(Exception $e, $response=false)
        {
    
            return config('app.debug') ? [
                'message' => $e->getMessage(),
                'exception' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
                'trace' => collect($e->getTrace())->map(function ($trace) {
                    return Arr::except($trace, ['args']);
                })->all(),
            ] : [
                'message' => $this->isHttpException($e) ? ($response ? $response['message']: $e->getMessage()) : 'Server Error',
            ];
        }
    

    Now navigate to the App\Exceptions\Handler class and paste the below code just above the render method:

    public function convertExceptionToArray(Exception $e, $response=false){
    
            if(!config('app.debug')){
                $statusCode=$e->getStatusCode();
                switch ($statusCode) {
                case 401:
                    $response['message'] = 'Unauthorized';
                    break;
                case 403:
                    $response['message'] = 'Forbidden';
                    break;
                case 404:
                    $response['message'] = 'Resource Not Found';
                    break;
                case 405:
                    $response['message'] = 'Method Not Allowed';
                    break;
                case 422:
                    $response['message'] = 'Request unable to be processed';
                    break;
                default:
                    $response['message'] = ($statusCode == 500) ? 'Whoops, looks like something went wrong' : $e->getMessage();
                    break;
                }
            }
    
            return parent::convertExceptionToArray($e,$response);
        }
    

    Basically, we overrided convertExceptionToArray method, prepared the response message, and called the parent method by passing the response as an argument.

    Note: This solution will not work for Authentication/Validation errors but most of the time these both errors are well managed by Laravel with proper human-readable response messages.

提交回复
热议问题