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.
Syntax:
Let's see below syntax and example:
try {
/* Write Your Code Here */
} catch (Exception $e) {
return $e->getMessage();
}
Example:
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:
<?php
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);
exit;
}
return response()->json($post);
}
}
Output:
string(44) "Exception Message: Undefined variable $data"
string(17) "Exception Code: 0"
string(17) "Exception String: ......"
It will help you....
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial