Laravel 9 Error Handling Tutorial Example




Laravel 9 Error Handling Tutorial Example

In this tutorial we will go over the demonstration of laravel 9 exception handling. We will look at example of laravel 9 exception handler. Here you will learn laravel 9 error handling. you can see laravel 9 exception handling example.

Sometimes we wrote code right but there is a possibility that if the user inputs the wrong data or something will wrong on the website then our user should not show an error, we can handle the error and display a proper message where is an issue and what they need to do.


Let's see below syntax and example:

try {

/* Write Your Code Here */

} catch (Exception $e) {

return $e->getMessage();



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


namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

use Exception;

class PostController extends Controller



* Display a listing of the resource.


* @return \Illuminate\Http\Response


public function show($id)


try {

$post = Post::find($data['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);



return response()->json($post);




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

string(17) "Exception Code: 0"

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

It will help you....

#Laravel 9