在 Laravel 中使用 try 和 catch 进行错误处理

Error handling with try and catch in Laravel

我想在我的应用程序中实现良好的错误处理,我强制使用此文件来捕获错误。

App\Services\PayUService

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

App\Controller\ProductController

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

这就是我得到的。

我不知道为什么 Laravel 没有将我重定向到该视图。 强制报错对吗?

您在 namespace 中,因此您应该使用 \Exception 指定全局命名空间:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

在您的代码中您使用了 catch (Exception $e),因此正在搜索 Exception in/as:

App\Services\PayUService\Exception

因为 App\Services\PayUService 里面没有 Exception class 所以它没有被触发。或者,您可以在 class 的顶部使用 use 语句,例如 use Exception;,然后您可以使用 catch (Exception $e).