Skip to main content
Quick Tip

Customize Exception Handler For API

Laravel 8 and below:

There's a method render() in App\Exceptions class:

public function render($request, Exception $exception)
{
if ($request->wantsJson() || $request->is('api/*')) {
if ($exception instanceof ModelNotFoundException) {
return response()->json(['message' => 'Item Not Found'], 404);
}
 
if ($exception instanceof AuthenticationException) {
return response()->json(['message' => 'unAuthenticated'], 401);
}
 
if ($exception instanceof ValidationException) {
return response()->json(['message' => 'UnprocessableEntity', 'errors' => []], 422);
}
 
if ($exception instanceof NotFoundHttpException) {
return response()->json(['message' => 'The requested link does not exist'], 400);
}
}
 
return parent::render($request, $exception);
}

Laravel 9 and above:

There's a method register() in App\Exceptions class:

public function register()
{
$this->renderable(function (ModelNotFoundException $e, $request) {
if ($request->wantsJson() || $request->is('api/*')) {
return response()->json(['message' => 'Item Not Found'], 404);
}
});
 
$this->renderable(function (AuthenticationException $e, $request) {
if ($request->wantsJson() || $request->is('api/*')) {
return response()->json(['message' => 'unAuthenticated'], 401);
}
});
$this->renderable(function (ValidationException $e, $request) {
if ($request->wantsJson() || $request->is('api/*')) {
return response()->json(['message' => 'UnprocessableEntity', 'errors' => []], 422);
}
});
$this->renderable(function (NotFoundHttpException $e, $request) {
if ($request->wantsJson() || $request->is('api/*')) {
return response()->json(['message' => 'The requested link does not exist'], 400);
}
});
}

Enjoyed This Tip?

Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.

Recent Courses

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.