Black Friday: coupon FRIDAY24 for 40% off Yearly/Lifetime membership! Read more here

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);
}
});
}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 67 courses (1172 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses