Laravel API, how to properly handle errors

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

    In my opinion I'd keep it simple.

    Return a response with the HTTP error code and a custom message.

    return response()->json(['error' => 'You need to add a card first'], 500);
    

    Or if you want to throw a caught error you could do :

       try {
         // some code
        } catch (Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    

    You can even use this for sending successful responses:

    return response()->json(['activeSubscription' => $this->getActiveSubscription()], 200);
    

    This way no matter which service consumes your API it can expect to receive the same responses for the same requests.

    You can also see how flexible you can make it by passing in the HTTP status code.

提交回复
热议问题