Laravel Error Handling

Created At: 2023-05-08 19:18:30 Updated At: 2023-09-14 22:31:36

Error catching should be one of your priorities when you develop api or application. But a lot of developers forget to do it. Even if they want to catch error or handle exceptions, they don't know how to do it. Here I have some tips and solutions for you.

You need to make the above changes in your code and run api test on postman. With this you would be able to catch the exact error you are facing. Do remember this type of error catching just during development phase. 

Because below we do special set up to find errors but in production you should not catch error like that. Cuz with this set up you are exposing some internal info with the outside world.

See different kinds of Laravel error

Throwable Interface

One of the ways you can catch error in Laravel is using Throwable interface. It's super easy. If you do a query, just wrap your query using try catch block and in the catch block use throwable.

try{
 // rest of your code here 
//because of catch() we will get the exact error

} catch (\Throwable $th) {
            return response()->json([
                'status' => false,
                'message' => $th->getMessage()
            ], 500);
}

If you put your query inside this, if you have syntax error, field error like database error, it will throw error in a nice format.

Now we will put our code inside this

   $result = Course::select('names', 'thumbnail', 'lesson_num', 'price', 'id')
                ->get();

            return response()->json([
                        'code' => 200,
                        'msg' => 'My course list is here',
                        'data' => $result
                ], 200);

Now inside the code, I have a filed names which is not correct. Now it will throw error in a beautiful readable format.

Without the throwable interface, you will have a completely different error reporting and hard to read.

Exceptions Handler

The other way to do it is to changing the Handler.php file inside app/Exceptions

See the initial code of register method.

 public function register(): void
    {
        $this->reportable(function (Throwable $e) {
            //
        });
    }

 

All we need to do is changing the body of the register method. Instead of returning reportable() we will return renderable(). Inside this we catch the error and return in a json format.

$this->renderable(function (Throwable $e) {
            //
            return response(['error' => $e->getMessage()], $e->getCode() ?: 400);
        });

You can learn about renderable() and reportable() from the official website.

After having, this you may test api endpoint in postman. It should be very helpful to see the exact error from postman and work on the error.

Comment

Add Reviews