Home » Php » php – Error handling with try and catch in Laravel

php – Error handling with try and catch in Laravel

Posted by: admin April 23, 2020 Leave a comment


I want to implement a good error handling in my app, I have forced this file for catching the error.


try {
  $this->buildXMLHeader; // Should be $this->buildXMLHeader();
} catch (Exception $e) {
        return $e;


function secTransaction(){
  if ($e) {
    return view('products.error', compact('e'));

And this is what I get.

enter image description here

I don’t know why Laravel is not redirecting me to the view.
Is the error forced right?

How to&Answers:

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

try {


} catch (\Exception $e) {

    return $e->getMessage();

In your code you’ve used catch (Exception $e) so Exception is being searched in/as:


Since there is no Exception class inside App\Services\PayUService so it’s not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).