Laravel 10 Try Catch Exception Handling Example

Exception handling allows you to gracefully terminate the execution of a specific block of code or the entire program when an error occurs. Instead of crashing, you can perform cleanup operations or notify the user about the error before exiting 

Syntax:

You have to use try catch as below syntax and you must need to use "use Exception" on top of file in laravel. 

try {

  
        /* Write Your Code Here */
      
      
      } catch (Exception $e) {
      
    
          return $e->getMessage();
      
      }

Example:

Here, we will show you controller file code and we will use "$input" variable in controller method that not define any more. it will generate error. so let's see bellow example: 


<?php
    
namespace App\Http\Controllers;
    
use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Exception;
    
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id): JsonResponse
    {
        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);
    }
}

Output:

string(44) "Exception Message: Undefined variable $input"

string(17) "Exception Code: 0"

string(17) "Exception String: ......"

 

Open Yor Browser and see output ,Thank You