API Exceptions in Laravel 5

I would like to catch all the usual exceptions (instances of the Exception class) from one of my controllers (or in the future in several controllers) in order to unify their behavior. I know how to make global exception handlers in Exceptions / Handler.php, but how can I limit them to a specific controller?

What I want to do is return such an array in JSON format whenever an exception is thrown in my API controller:

 [ 'error' => 'Internal error occurred.' ] 

I could decide to throw my own exception class, perhaps ApiException , but I want to also handle third-party exceptions, such as database errors.

Should I pass some value to the request object directly? If so, how? Or maybe there is another way?

+5
source share
3 answers

If you want to visualize a separate type of exception for a specific controller, you can use the query object to check the current controller:

<strong> Exceptions /handler.php

 public function render($request, Exception $e) { if($request->route()->getAction()["controller"] == "App\Http\Controllers\ ApiController@index "){ return response()->json(["error" => "An internal error occured"]); } return parent::render($request, $e); } 
+3
source

You can also filter the query by their path patterns.

Go to app\Exceptions\Handler.php :

 public function render($request, \Exception $e) { /* Filter the requests made on the API path */ if ($request->is('api/*)) { return response()->json(["error" => "An internal error occured"]); } return parent::render($request, $e); } 
+2
source

You can do it:

create exception class

 class APIException extends Exception{ } 

then throw it off the controller

 throw new APIException('api exception'); 

and catch it from Exceptions / Handler.php

 public function render($request, Exception $e) { if ($e instanceof APIException){ return response(['success' => false, 'data' => [], 'message' => $e->getMessage(), 401); } if ($e instanceof SomeException){ return response(['success' => false, 'data' => [], 'message' => 'Exception'], 401); } return parent::render($request, $e); } 
+1
source

All Articles