Skip to content

Commit 8d8a409

Browse files
author
ahmadhuss
committed
feat: API Custom Exception handling errors Tip 1,2,3
1 parent a9ef0ca commit 8d8a409

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

app/Exceptions/Handler.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace App\Exceptions;
44

5+
use Illuminate\Database\Eloquent\ModelNotFoundException;
56
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
67
use Throwable;
78

@@ -38,4 +39,20 @@ public function register()
3839
//
3940
});
4041
}
42+
43+
44+
// Override the render method i.e. coming from the class Handler
45+
public function render($request, Throwable $e)
46+
{
47+
// To set the correct API error response for the findOrFail($id)
48+
if ($e instanceof ModelNotFoundException) {
49+
// str_replace(find:required,replace:required,string,count) => Returns a string or an array with the replaced values
50+
return response()->json([
51+
'error' => 'Entry for '.str_replace('App\\Models\\', '', $e->getModel()). ' not found',
52+
'model' => $e->getModel()
53+
], 404);
54+
}
55+
56+
return parent::render($request, $e);
57+
}
4158
}

routes/api.php

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,3 +35,36 @@
3535
Route::get('products', [ProductController::class, 'index']);
3636
// "{product}" will use Route Model Binding
3737
Route::get('products/{product}', [ProductController::class, 'show']);
38+
39+
40+
/**
41+
* Handling API Exceptions
42+
*
43+
* Tip 1. Switch APP_DEBUG=false Even Locally
44+
*
45+
* If someone calls API route that doesn’t exist, By default, you get this response from API:
46+
* { "message": ""}
47+
*
48+
* Tip 2. Unhandled Routes – Fallback Method
49+
* Route::fallback() method at the end of routes/api.php, handling all the routes that weren’t matched.
50+
*
51+
* The result will be the same 404 response, but now with error message that give some more information
52+
* about what to do with this error.
53+
*/
54+
Route::fallback(function () {
55+
return response()->json(['message' => 'Page Not Found. If error persists, contact API Owner.'], 404);
56+
});
57+
58+
/**
59+
* Tip 3. Override 404 ModelNotFoundException
60+
*
61+
* Most often exceptions is that some model object is not found, usually thrown by Model::findOrFail($id).
62+
* If we leave it at that, here’s the typical message your API will show:
63+
* {
64+
* "message": "No query results for model [App\\Models\\Category] 19"
65+
* }
66+
*
67+
* We can do that in app/Exceptions/Handler.php (remember that file, we will come back to it multiple times later),
68+
* in render() method:
69+
*/
70+

0 commit comments

Comments
 (0)