In this short article, we will learn how we can handle 404 error for API as well as webpage. While building API, we need JSON response with the useful message whereas in web page load, we need a 404 page. We can achieve this with a few lines of code.
First of all, we will try the route method. In this method, we will add the below code at the end of api.php
to handle the routes if non of the above routes are matched. What it does is basically if non of the routes are matched, it catches the route and returns a JSON response with a message instead of a 404 page.
Route::any('{path}', function() {
return response()->json([
'success' => false,
'message' => 'Route not found'
], 404);
})->where('path', '.*');
However, this has some limitations. If there are packages where routes are defined then those routes will never hit because the api.php is rendered first and the packages’ routes are rendered. Thus, it won’t work under those conditions. Thus, below methods works perfectly fine for all conditions.
To handle the limitation of the above code, we will customize handler.php file. The limitation of the below code is that you need to have your API route prefix with “/api/”. Simply add the below code in your app/Exceptions/Handler.php
.
//import class on the top
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
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);
}
What it does is that, if there is an exception that is an instance of NotFoundHttpException
and if the request has “/api/” in its route, then the JSON response of Route not found will be returned.