Exception handling in laravel
Hello buddy in this article we will get to know how we can handle the exception in laravel.
We will implement our try-catch logic in our laravel controller.But before moving forward do you know what is exception handling, I think first we have to understand that what is exception handling, and then we will see how we can implement exception handling in laravel.
What is exception handling?
Exception handling is used to change the normal flow of the code execution if a specified error (exceptional) condition occurs. This condition is called an exception.
Now you have the basic idea of what is exception handling, now we will implement this exception concept with our laravel.
Syntax of exception handling
try {
/* Write Your Code Here */
} catch (Exception $e) {
return $e->getMessage();
}
Example
<?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);
}
}
Output
string(44) "Exception Message: Undefined variable $input"
string(17) "Exception Code: 0"
string(17) "Exception String: ......"
Now you must have the idea about exception handling, and I thought now you are able implement it with your code, Don’t forgot to rate the article.