Laravel API, how to properly handle errors

后端 未结 6 774
后悔当初
后悔当初 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:25

    I think it would be better to modify existing behaviour implemented in app/Exceptions/Handler.php than overriding it.

    You can modify JSONResponse returned by parent::render($request, $exception); and add/remove data.

    Example implementation:
    app/Exceptions/Handler.php

    use Illuminate\Support\Arr;
    
    // ... existing code
    
    public function render($request, Exception $exception)
    {
        if ($request->is('api/*')) {
            $jsonResponse = parent::render($request, $exception);
            return $this->processApiException($jsonResponse);
        }
    
        return parent::render($request, $exception);
    }
    
    protected function processApiException($originalResponse)
    {
        if($originalResponse instanceof JsonResponse){
            $data = $originalResponse->getData(true);
            $data['status'] = $originalResponse->getStatusCode();
            $data['errors'] = [Arr::get($data, 'exception', 'Something went wrong!')];
            $data['message'] = Arr::get($data, 'message', '');
            $originalResponse->setData($data);
        }
    
        return $originalResponse;
    }
    

提交回复
热议问题