Various answers (JSON and webpage) in API and website for Laravel 404 and 500?
I want to show various API and website responses. In the api response, I want to show json response with 404 and 500 for the type of exception, mainly for routes.
If the user tries to request a route and the route is not found, I want to show the response in the json response for the API and the webpage for the website.
I know and try the code in app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
if ($exception instanceof NotFoundHttpException) {
if ($request->expectsJson()) {
return response()->json(['error' => 'Not Found'], 404);
}
return response()->view('404', [], 404);
}
return parent::render($request, $exception);
}
https://laravel.com/docs/5.4/errors#http-exceptions
but couldn't anyone help me how can I set different answers for error pages.
source to share
Expects JSON to be about headers, I don't like this solution for API errors, to be honest you can access it through a browser. My solution in most cases is filtered by URL-address, because most often it begins with "api/..."
that you can do this: $request->is('api/*')
.
If you have a route / api it will work, otherwise changes to the request might be triggered.
public function render($request, Exception $exception)
{
if ($exception instanceof NotFoundHttpException) {
if ($request->is('api/*')) {
return response()->json(['error' => 'Not Found'], 404);
}
return response()->view('404', [], 404);
}
return parent::render($request, $exception);
}
source to share
I am using Laravel 5.5.28 and add this to app/Exceptions/Handler.php
public function render($request, Exception $exception)
{
// Give detailed stacktrace error info if APP_DEBUG is true in the .env
if ($request->wantsJson()) {
// Return reasonable response if trying to, for instance, delete nonexistent resource id.
if ($exception instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
return response()->json(['data' => 'Resource not found'], 404);
}
if ($_ENV['APP_DEBUG'] == 'false') {
return response()->json(['error' => 'Unknown error'], 400);
}
}
return parent::render($request, $exception);
}
This assumes that your API calls will have a header with a key Accept
and value application/json
.
Then the non-existent web route returns the expected
Sorry, the page you are looking for was not found.
and the non-existent API resource returns a JSON 404 payload.
Found information here .
You can combine this with the answer by looking for an instance NotFoundHttpException
to catch 500. I suppose, however, that a stack trace would be preferable.
source to share