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
Error handling with try and catch in Laravel
提问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.
这就是我得到的。
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 namespace
so you should use \Exception
to 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 Exception
is being searched in/as:
在你的代码已经使用了catch (Exception $e)
这么Exception
被搜查/为:
App\Services\PayUService\Exception
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)
.
由于里面没有Exception
类,App\Services\PayUService
所以它不会被触发。或者,您可以use
在类的顶部使用一条语句,例如use Exception;
,然后您可以使用catch (Exception $e)
.