I was wondering if there is a way to catch all the exceptions that are thrown in a laravel app and store them in database ?
I have been looking at some packages but coudn't find anything that tells where and how to catch the exceptions.
Because exceptions are objects, they all extend a built-in Exception class (see Throwing Exceptions in PHP), which means that catching every PHP exception thrown is as simple as type-hinting the global exception object, which is indicated by adding a backslash in front: try { // ... } catch ( \Exception $e ) { // ... }
HTTP ExceptionsLaravel makes it easy to display custom error pages for various HTTP status codes. For example, if you wish to customize the error page for 404 HTTP status codes, create a resources/views/errors/404. blade. php . This file will be served on all 404 errors generated by your application.
To do that, you can specify Route::fallback() method at the end of routes/api. php, handling all the routes that weren't matched. Route::fallback(function(){ return response()->json([ 'message' => 'Page Not Found. If error persists, contact [email protected]'], 404); });
for catch all errors and log them you need to edit App\Exceptions\Handler
file like this
public function render($request, Exception $exception)
{
if ($exception){
// log the error
return response()->json([
'status' => $exception->getStatusCode(),
'error' => $exception->getMessage()
]);
}
return parent::render($request, $exception);
}
As stated in the Docs,
You need to have to customize the render()
method of App\Exceptions\Handler
.
Edit the app/Exceptions/Handler.php:
public function render($request, Exception $e)
{
$error =$e->getMessage();
//do your stuff with the error message
return parent::render($request, $exception);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With