Customize Exception Handler For API

Laravel 8 and below:

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

1public function render($request, Exception $exception)
2 {
3 if ($request->wantsJson() || $request->is('api/*')) {
4 if ($exception instanceof ModelNotFoundException) {
5 return response()->json(['message' => 'Item Not Found'], 404);
6 }
7 
8 if ($exception instanceof AuthenticationException) {
9 return response()->json(['message' => 'unAuthenticated'], 401);
10 }
11 
12 if ($exception instanceof ValidationException) {
13 return response()->json(['message' => 'UnprocessableEntity', 'errors' => []], 422);
14 }
15 
16 if ($exception instanceof NotFoundHttpException) {
17 return response()->json(['message' => 'The requested link does not exist'], 400);
18 }
19 }
20 
21 return parent::render($request, $exception);
22 }

Laravel 9 and above:

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

1public function register()
2{
3 $this->renderable(function (ModelNotFoundException $e, $request) {
4 if ($request->wantsJson() || $request->is('api/*')) {
5 return response()->json(['message' => 'Item Not Found'], 404);
6 }
7 });
8 
9 $this->renderable(function (AuthenticationException $e, $request) {
10 if ($request->wantsJson() || $request->is('api/*')) {
11 return response()->json(['message' => 'unAuthenticated'], 401);
12 }
13 });
14 $this->renderable(function (ValidationException $e, $request) {
15 if ($request->wantsJson() || $request->is('api/*')) {
16 return response()->json(['message' => 'UnprocessableEntity', 'errors' => []], 422);
17 }
18 });
19 $this->renderable(function (NotFoundHttpException $e, $request) {
20 if ($request->wantsJson() || $request->is('api/*')) {
21 return response()->json(['message' => 'The requested link does not exist'], 400);
22 }
23 });
24}

Like our articles?

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