Search code examples
laravelapi-designlaravel-5.5dingo-api

Laravel Dingo API - Only log 500 error, never send error details via api?


I made the below controller to demonstrate the issue of handling 500 errors I am having with dingo api in laravel. I want to be able to detect when a 500 error will be thrown so it never makes it to the client (as it is too much details to share with the client and they should only be logged by Laravel).

The methodgetUser() returns a 500 error intentionally due to the typo firsgt()

class TestController extends Controller {
  public function getUser() {
    $data = User::firsgt(); //returns 500 error
    return $data;
  }
}

This is what the client sees: enter image description here

In my controllers, I handle errors manually by returning a success/error json response from within the controllers, but if an error occurs that I did not expect, the api returns it and it has too much details for the client to see. Instead, these unexpected errors should bubble up to some sort of handler to return a generic error occurred response. In Laravel, setting APP_DEBUG = false in .env works for laravel (but not for dingo api), this has no effect and the full error is returned to the client. Looking for a safety net for errors that slip through the cracks.

How can we return an error message like 'Error occurred' instead of the too much details for client 'Call to undefined method App\User::firsgt()'?

Note: I don't want to handle it one by one for each controller method, but instead capture any 500 before it is returned to client, and return the custom 500 generic message 'Error occurred'


Solution

  • You should check your dingo config and set these two parameters to false.

    APP_DEBUG=false
    API_DEBUG=false
    

    If you still encounter the issue, just as suggested in the comment ensure you are in production.

    Finally if you are still having the same issues (which by now normally should not exist after setting those fields to false) then you might be interested in checking this issue (date back since 2015).

    The fix from one of the comment says (verbatim):

    app(\Dingo\Api\Exception\Handler::class)->register(function (\Exception $exception) {
        if (!env('API_DEBUG') && !$exception instanceof \Symfony\Component\HttpKernel\Exception\HttpException) {
            // Whatever other handling you want goes here..
    
            // Mimic the normal API response with a different message
            return \Response::make([
                'message'     => 'Internal server error',
                'status_code' => 500,
            ], 500);
        }
    });
    

    Beware that I didnt test this myself.