laravel try catch error handling (exception in controller)

Rate this post

Today, We want to share with you laravel try catch.In this post we will show you Laravel Exceptions: How to Catch, Handle and Create Your Own, hear for PHP Laravel Exception Handling we will give you demo and example for implement.In this post, we will learn about Php Try Catch Block Exception Handling with an example.

Introduction To Exception Handling in Laravel

in Laravel, All exceptions are handled by the App\Exceptions\Handler class.

List of available built-in exception classes since PHP 7.4:

Read Also:  PHP Crop Resize Image while Uploading using jquery plugin

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

OR

App\Services\PayUService\Exception

<?php
try {
    $var_msg = "This is an exception example";
    throw new Exception($var_msg);
}
catch (Exception $e) {
    echo "Message: " . $e->getMessage();
    echo "";
    echo "getCode(): " . $e->getCode();
    echo "";
    echo "__toString(): " . $e->__toString();
}
?>

The entire handling process is wrapped inside a try…catch:

public function store(Request $request)
 {  
    try   
    {  
        $product = new PostComment();  
        $product->content = $request['product'];  
        $product->user_id = Auth::user()->id;  
        $product->product_id = $request['productId'];  
        $product->save();  
        $product = Product::where('id', '=', $product->product_id)->first();  
        $product->updated_at = $product->created_at;  
        $product->update();  
    }    
    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 product !!!');  
        return redirect()->back();  

    }  
    request()->session()->flash('successMessage', 'Comment has been successfully added !!!');  
    return redirect()->back();  
}  

Free Live Chat for Any Issue

Example 2

try {
    App\Models\Product::find(1);
} catch (\Exception $ex) {
   dd('Exception block', $ex);
} catch (\Throwable $ex) {
   dd('Throwable block', $ex);
}

Download

I hope you get an idea about Laravel – Error & Exception Handling.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.