Laravel Error Handling

Laravel Error Handling

    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.

    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.

    Courses


    Recent posts