Tag Archives: dingo

Handle exceptions with Dingo

Normally, when an uncaught exception is thrown in Laravel, the render method in app/Exceptions/Handler.php is called in. The exception object is passed in and you are able to respond to it in any way you please.

However, Dingo seems to tamper with this functionality causing the render method to never be called. It’s not even called when the exception is caused by a non-API route. To work around this, add the following to the boot method of you app/Providers/AppServiceProvider.php file.


public function boot()
{
    // Handle site-wide exceptions here
    app('Dingo\Api\Exception\Handler')->register(function (\Exception $ex) {
        // Handle Exception here
        // e.g. return view('errors.index');
    )};
}

To test for HTTP exception, such as a 404 error, add this use line to the top.


use Symfony\Component\HttpKernel\Exception\HttpException;

Now you can test for the 404 status code (or any other HTTP status code) like this.


use Symfony\Component\HttpKernel\Exception\HttpException;
public function boot()
{
    // Handle site-wide exceptions here
    app('Dingo\Api\Exception\Handler')->register(function (\Exception $ex) {
        if ($ex instanceof HttpException && $ex->getStatusCode() == 404){
            return view('errors.404-error');
        }else{
            return view('errors.general-error');
        }
        
    )};
}