Laravel Exception/Error Handling

In this article, you will learn how to handle errors in Laravel. This article will show you how to use an exception handler in Laravel. You can get an idea of how laravel handles errors. This article will show a simple example of handling errors in Laravel. We will use try-catch to handle the exception.


Why does our PHP Laravel app need to use try-catch? We're going to tell you why. Sometimes we write the code right, but if the user enters the wrong information or something goes wrong on the website, our user shouldn't get an error message. Instead, we can handle the error and show the user what's wrong and what they need to do. So, if you need to try-catch, you can use the same thing whenever possible.


You are required to use try-catch in the following syntax, and you are also required to use "use Exception" at the very top of the file when working in Laravel.


try {
  /* Write Your Code Here */
}

 catch (Exception $e) {
    return $e->getMessage();
}


Here is the code for the controller file, and we'll use the "$input" variable in a controller method that is no longer defined. It will generate the error. So let's look at an example below:


<?php
   
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Models\User;
use Exception;
   
class UserController extends Controller
{
    /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
    public function show($id)
    {
        try {
            $user = User::find($input['id']);
        } catch (Exception $e) {
             
            $message = $e->getMessage();
            var_dump('Exception Message: '. $message);
 
            $code = $e->getCode();      
            var_dump('Exception Code: '. $code);
 
            $string = $e->__toString();      
            var_dump('Exception String: '. $string);
            exit;
        }
        return response()->json($user);
    }
}