I am building a restful api with laravel and adding a few more custom attributes to the laravel exception handler. Looking for the best way to do it.
I am currently using Laravel 6 and if I setup the Accept header to application/json, exceptions are returned in the json format. I still want to keep the existing logic on how laravel handles exception through render method like so:
public function render($request, Exception $exception)
{
return parent::render($request, $exception);
}
The current method returns only message when debug is false.
{
"message": "No query results for model [App\\Model]"
}
I would like to add more attributes to the response data for the existing exception and custom ones:
{
"message": "No query results for model [App\\Model]",
"type": "exception",
"url": "link to api docs",
"id": "#id of the request"
}
I don't want to rewrite all the logic within render() but want to keep it as is by just adding these attributes.
i use this
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException || $exception instanceof NotFoundExeptionMessage){
return $this->NotFoundExeptionMessage($request, $exception);
}
return parent::render($request, $exception);
}
this code check the error and pass it to the NotFoundExeptionMessage if header sets application/json and else return a render
and in second
public function NotFoundExeptionMessage($request, Exception $exception): JsonResponse
{
return $request->expectsJson()
? new JsonResponse([
'data' => 'Not Found',
'Status' => 'Error'
], 404)
: parent::render($request, $exception);
}
i check if request want a json response we return a json message
and else we return a render
you can customize jsonresponse
good luck
Related
I want to return a JSON response instead of the default 404 error page when ModelNotFoundException occurs. To do this, I wrote the following code into app\Exceptions\Handler.php :
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'error' => 'Resource not found'
], 404);
}
return parent::render($request, $exception);
}
However it doesn't work. When the ModelNotFoundException occurs, Laravel just shows a blank page. I find out that even declaring an empty render function in Handler.php makes Laravel display a blank page on ModelNotFoundException.
How can I fix this so it can return JSON/execute the logic inside the overriden render function?
In Laravel 8x, You need to Rendering Exceptions in register() method
use App\Exceptions\CustomException;
/**
* Register the exception handling callbacks for the application.
*
* #return void
*/
public function register()
{
$this->renderable(function (CustomException $e, $request) {
return response()->view('errors.custom', [], 500);
});
}
For ModelNotFoundException you can do it as below.
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
public function register()
{
$this->renderable(function (NotFoundHttpException $e, $request) {
return response()->json(...);
});
}
By default, the Laravel exception handler will convert exceptions into an HTTP response for you. However, you are free to register a custom rendering Closure for exceptions of a given type. You may accomplish this via the renderable method of your exception handler. Laravel will deduce what type of exception the Closure renders by examining the type-hint of the Closure:
More info about the error exception
This code doesn't work for me (in Laravel 8.74.0):
$this->renderable(function (ModelNotFoundException$e, $request) {
return response()->json(...);
});
Don't know why, but ModelNotFoundException is directly forwarded to NotFoundHttpException (which is a part of Symfony Component) that used by Laravel and will ultimately triggers a 404 HTTP response. My workaround is checking the getPrevious() method of the exception:
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->is('api/*')) {
if ($e->getPrevious() instanceof ModelNotFoundException) {
return response()->json([
'status' => 204,
'message' => 'Data not found'
], 200);
}
return response()->json([
'status' => 404,
'message' => 'Target not found'
], 404);
}
});
And then we will know that this exception come from ModelNotFoundException and return a different response with NotFoundHttpException.
Edit
This is why ModelNotFoundException thrown as NotFoundHttpException
This one is my Handler file:
use Throwable;
public function render($request, Throwable $exception)
{
if( $request->is('api/*')){
if ($exception instanceof ModelNotFoundException) {
$model = strtolower(class_basename($exception->getModel()));
return response()->json([
'error' => 'Model not found'
], 404);
}
if ($exception instanceof NotFoundHttpException) {
return response()->json([
'error' => 'Resource not found'
], 404);
}
}
}
This one is only for all request in API route. If you want to catch all request, so remove the first if.
Please note that by default Laravel emits a JSON representation of an exception ONLY when you send a request with the header parameter Accept: application/json! For all other requests, Laravel sends normal HTML rendered output.
I have a controller entry point where I execute another method from my ProductService inside a try catch block, I pretend to catch all exceptions that may occur inside $this->productService->create() method, except for Validation errors, if it's a validation error $e->getMessage() won't do, since I'll get generic response "Given data was invalid" instead of full custom messages. After reading some, I decided to use render method in laravel Handler class, I added this:
//In order to react to validation exceptions I added some logic to render method, but it won't actually work, I'm still getting normal exception message returned.
public function render($request, Exception $exception)
{
if ($request->ajax() && $exception instanceof ValidationException) {
return response()->json([
'message' => $e->errors(),
],422);
}
return parent::render($request, $exception);
}
However I'm still getting the default message, this means that my catch block is catching normal exception instead of my custom render method...
In my controller, try catch block looks like this:
try
{
$this->productService->create($request);
return response()->json([
'product' => $product,
], 200);
}
//I want to catch all exceptions except Validation fails here, and return simple error message to view as
json
catch (\Exception $e)
{
return response()->json([
'message' => $e->getMessage(),
], $e->getStatus() );
}
Also, in ValidationException, I cannot use $e->getCode, $e->getStatus(), it will always return 0 or sometimes 1, afaik it should be 422, that's why in my render method I'm manually returning 422. In my try catch block with normal Exceptions $e->getCode() works correctly, why is that?
In your render function, you are referencing an error instance that isn't defined, you have define Exception $exception but you are referencing $e->errors();
You code should be:
public function render($request, Exception $exception)
{
if ($request->ajax() && $exception instanceof ValidationException) {
return response()->json([
'message' => $exception->errors(),
],422);
}
return parent::render($request, $exception);
}
Change $e->errors(); to $exception->errors();
I want to return a json response when an api call is made to a laravel 5.7 app api route when the model is not found. To do this I have modified the render() method of app\Exceptions\Handler.php like this
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && $request->wantsJson()) {
return response()->json(['message' => 'Not Found!'], 404);
}
return parent::render($request, $exception);
}
and my controller show() method is using a Book model like this
public function show(Book $book)
{
return new BookResource($book->load('ratings'));
}
Test on postman, a get call to localhost:8000/api/books/1 (id 1 has been deleted) keeps returning the default laravel 404 not found page instead of json.
Have I missed a step or something? I also noticed that adding a conditional statement inside the controller show() method like this
public function show(Book $book)
{
if ($book) {
return new BookResource($book->load('ratings'));
} else {
return response()->json(['message' => 'Not found'], 404);
}
}
returns the same html result instead of json.
What will be the proper way to handle this scenario?
Your code is correct. The problem is that you are probably testing it on a Local environment so in your .env you have set:
APP_DEBUG=true, switch it to APP_DEBUG=false and you will see your custom message.
PS: $request->wantsJson() is not necessary if your clients send the correct header info, eg: 'accept:application/json'
You can remove $request->wantsJson
or you can set the header in your request "Accept" => "application/json"
May this can help you:
public function render($request, Exception $exception)
{
if ($exception instanceof ModelNotFoundException && ($request->wantsJson() || $request->ajax())) {
return response()->json(['message' => 'Not Found!'], 404);
}
return parent::render($request, $exception);
}
I'm developing a Laravel 5.6 API and I'm using Resources and Collections, Route Model Binding.
To show an item, I currently use following code in my controller:
public function show(Todo $todo)
{
TodoResource::withoutWrapping();
return new TodoResource($todo);
}
In the Exceptions > Handler.php I have the following:
public function render($request, Exception $exception)
{
// This will replace our 404 response with
// a JSON response.
if ($exception instanceof ModelNotFoundException) {
return response()->json([
'error' => 'Resource not found'
], 404);
}
return parent::render($request, $exception);
}
This works perfectly when the item is found in the database. If the item is not in the database I get a (when using a browser):
"Sorry, the page you are looking for could not be found"
When using POSTMAN rest client, I'm getting
{
"message": "No query results for model [App\\Todo].",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
....
....
I would like to simply retrieve a 404 error with text "Resource not found", using both a browser or POSTMAN.
* Update with Routing info *
In my api.php, I have the following:
Route::apiResource('todos', 'TodoController');
Route::fallback(function () {
return response()->json(['message' => 'Not Found!'], 404);
});
In web.php, I have:
Route::Resource('todos', 'TodoController');
What is the best way to achieve this?
Make sure to alias the exception class you are checking for.
use Illuminate\Database\Eloquent\ModelNotFoundException;
Without this you are checking for an instance of App\Exceptions\ModelNotFoundException.
Im just move to laravel 5 and im receiving errors from laravel in HTML page. Something like this:
Sorry, the page you are looking for could not be found.
1/1
NotFoundHttpException in Application.php line 756:
Persona no existe
in Application.php line 756
at Application->abort('404', 'Person doesnt exists', array()) in helpers.php line
When i work with laravel 4 all works fine, the errors are in json format, that way i could parse the error message and show a message to the user. An example of json error:
{"error":{
"type":"Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"message":"Person doesnt exist",
"file":"C:\\xampp\\htdocs\\backend1\\bootstrap\\compiled.php",
"line":768}}
How can i achieve that in laravel 5.
Sorry for my bad english, thanks a lot.
I came here earlier searching for how to throw json exceptions anywhere in Laravel and the answer set me on the correct path. For anyone that finds this searching for a similar solution, here's how I implemented app-wide:
Add this code to the render method of app/Exceptions/Handler.php
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse($e->getMessage(), 422);
}
Add this to the method to handle objects:
if ($request->ajax() || $request->wantsJson()) {
$message = $e->getMessage();
if (is_object($message)) { $message = $message->toArray(); }
return new JsonResponse($message, 422);
}
And then use this generic bit of code anywhere you want:
throw new \Exception("Custom error message", 422);
And it will convert all errors thrown after an ajax request to Json exceptions ready to be used any which way you want :-)
Laravel 5.1
To keep my HTTP status code on unexpected exceptions, like 404, 500 403...
This is what I use (app/Exceptions/Handler.php):
public function render($request, Exception $e)
{
$error = $this->convertExceptionToResponse($e);
$response = [];
if($error->getStatusCode() == 500) {
$response['error'] = $e->getMessage();
if(Config::get('app.debug')) {
$response['trace'] = $e->getTraceAsString();
$response['code'] = $e->getCode();
}
}
return response()->json($response, $error->getStatusCode());
}
Laravel 5 offers an Exception Handler in app/Exceptions/Handler.php. The render method can be used to render specific exceptions differently, i.e.
public function render($request, Exception $e)
{
if ($e instanceof API\APIError)
return \Response::json(['code' => '...', 'msg' => '...']);
return parent::render($request, $e);
}
Personally, I use App\Exceptions\API\APIError as a general exception to throw when I want to return an API error. Instead, you could just check if the request is AJAX (if ($request->ajax())) but I think explicitly setting an API exception seems cleaner because you can extend the APIError class and add whatever functions you need.
Edit: Laravel 5.6 handles it very well without any change need, just be sure you are sending Accept header as application/json.
If you want to keep status code (it will be useful for front-end side to understand error type) I suggest to use this in your app/Exceptions/Handler.php:
public function render($request, Exception $exception)
{
if ($request->ajax() || $request->wantsJson()) {
// this part is from render function in Illuminate\Foundation\Exceptions\Handler.php
// works well for json
$exception = $this->prepareException($exception);
if ($exception instanceof \Illuminate\Http\Exception\HttpResponseException) {
return $exception->getResponse();
} elseif ($exception instanceof \Illuminate\Auth\AuthenticationException) {
return $this->unauthenticated($request, $exception);
} elseif ($exception instanceof \Illuminate\Validation\ValidationException) {
return $this->convertValidationExceptionToResponse($exception, $request);
}
// we prepare custom response for other situation such as modelnotfound
$response = [];
$response['error'] = $exception->getMessage();
if(config('app.debug')) {
$response['trace'] = $exception->getTrace();
$response['code'] = $exception->getCode();
}
// we look for assigned status code if there isn't we assign 500
$statusCode = method_exists($exception, 'getStatusCode')
? $exception->getStatusCode()
: 500;
return response()->json($response, $statusCode);
}
return parent::render($request, $exception);
}
On Laravel 5.5, you can use prepareJsonResponse method in app/Exceptions/Handler.php that will force response as JSON.
/**
* Render an exception into an HTTP response.
*
* #param \Illuminate\Http\Request $request
* #param \Exception $exception
* #return \Illuminate\Http\Response
*/
public function render($request, Exception $exception)
{
return $this->prepareJsonResponse($request, $exception);
}
Instead of
if ($request->ajax() || $request->wantsJson()) {...}
use
if ($request->expectsJson()) {...}
vendor\laravel\framework\src\Illuminate\Http\Concerns\InteractsWithContentTypes.php:42
public function expectsJson()
{
return ($this->ajax() && ! $this->pjax()) || $this->wantsJson();
}
I updated my app/Exceptions/Handler.php to catch HTTP Exceptions that were not validation errors:
public function render($request, Exception $exception)
{
// converts errors to JSON when required and when not a validation error
if ($request->expectsJson() && method_exists($exception, 'getStatusCode')) {
$message = $exception->getMessage();
if (is_object($message)) {
$message = $message->toArray();
}
return response()->json([
'errors' => array_wrap($message)
], $exception->getStatusCode());
}
return parent::render($request, $exception);
}
By checking for the method getStatusCode(), you can tell if the exception can successfully be coerced to JSON.
If you want to get Exception errors in json format then
open the Handler class at App\Exceptions\Handler and customize it.
Here's an example for Unauthorized requests and Not found responses
public function render($request, Exception $exception)
{
if ($exception instanceof AuthorizationException) {
return response()->json(['error' => $exception->getMessage()], 403);
}
if ($exception instanceof ModelNotFoundException) {
return response()->json(['error' => $exception->getMessage()], 404);
}
return parent::render($request, $exception);
}