DEV Community

loading...

Handle Exception Error in Laravel using Rescue Helper

techdurjoy
・2 min read

If you want to make your web application robust, you get to handle those quirky and unpredictable exceptions. And the way you do that in PHP is by using try-catch blocks in your code. The same applies in the case of Laravel as well.

The traditional way

So, for instance, if you want to handle the exception when something goes wrong when saving/updating the model record, you can handle exceptions like so.

public function store(Request $request)
{

try

{

$comment = new BlogComment();

$comment->content = $request['comment'];

$comment->user_id = Auth::user()->id;

$comment->blog_id = $request['ticketId'];

$comment->save();
} catch(Exception $e) {
if (!($e instanceof SQLException)) {
app()->make(\App\Exceptions\Handler::class)->report($e);
// Report the exception if you don't know what actually caused it
}
request()->session()->flash('unsuccessMessage', 'Failed to add comment.');

return redirect()->back();
}
}

As you can tell, we’re using Laravel’s in-built error handling in the catch block to report the exception if it occurs.

Now, this is perfectly fine but do you know there’s a slicker and a cleaner way in Laravel that you can use to make this even shorter. Enter the rescue() helper.

The rescue() helper

Laravel provided this rescue() helper in which you can pass in the piece of code as a closure for which you want to handle exceptions. The helper will execute the given closure and catches any exceptions that occur during its execution. All exceptions that are caught will be sent to the exception handler.

So, if we want to rewrite the previous example using the rescue() helper, we can do it like so.

Handle Exception Error in Laravel using Rescue Helper

Fetch HTTP Client Response as Collection in Laravel 8.x

Discussion (0)