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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33444029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:29:40  来源:igfitidea点击:

Error handling with try and catch in Laravel

phplaravelerror-handlingtry-catch

提问by suarsenegger

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

我想在我的应用程序中实现一个很好的错误处理,我已经强制使用这个文件来捕获错误。

App\Services\PayUService

应用\服务\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'));
  }
}

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?

我不知道为什么 Laravel 没有将我重定向到视图。错误强制正确吗?

回答by The Alpha

You are inside a namespaceso you should use \Exceptionto specify the global namespace:

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

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

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

在你的代码已经使用了catch (Exception $e)这么Exception被搜查/为:

App\Services\PayUService\Exception

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

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