Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch all exceptions in Laravel

Tags:

laravel

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.

like image 810
PrStandup Avatar asked Jan 31 '18 07:01

PrStandup


People also ask

How can I catch exception in php?

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 ) { // ... }

What is exceptions in laravel?

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.

How does laravel handle exception in API?

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


2 Answers

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);
}
like image 83
Milad Teimouri Avatar answered Nov 10 '22 05:11

Milad Teimouri


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);
}
like image 42
Sapnesh Naik Avatar answered Nov 10 '22 05:11

Sapnesh Naik