如何正确捕获 PHP 异常 (Laravel 5.1)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31508223/
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
How to properly catch PHP exceptions (Laravel 5.1)
提问by Joel Joel Binks
I have some code that makes db calls and network requests and I have it wrapped in a try/catch. The problem is that I can never catch the exceptions, and they don't appear to be fatal exceptions:
我有一些代码可以进行 db 调用和网络请求,并将它封装在 try/catch 中。问题是我永远无法捕获异常,而且它们似乎不是致命的异常:
try {
// make db requests and network calls
} catch (Exception $e) {
// handle exception
}
Namely, I encounter exceptions such as these:
也就是说,我遇到了以下异常:
[Illuminate\Database\QueryException]
[PDOException]
[InvalidArgumentException]
Is there a way to catch these exceptions? Do I need to be explicit for each possible type of exception object (meaning I must create many try/catches), or is there a recommended way of catching non fatal exceptions?
有没有办法捕捉这些异常?我是否需要为每种可能的异常对象类型明确(意味着我必须创建许多尝试/捕获),或者是否有推荐的方法来捕获非致命异常?
回答by jedrzej.kurylo
Make sure you're using your namespaces properly, by including the Exception class at the top of your controller like this:
确保正确使用命名空间,方法是在控制器顶部包含 Exception 类,如下所示:
Use Exception;
If you use a class without providing its namespace, PHP looks for the class in the current namespace. Exceptionclass exists in global namespace, so if you do that try/catch in some namespaced code, e.g. your controller or model, you'll need to do:
如果您使用一个类而不提供其命名空间,PHP 会在当前命名空间中查找该类。异常类存在于全局命名空间中,因此如果您在某些命名空间代码中执行 try/catch,例如您的控制器或模型,则需要执行以下操作:
try {
//code causing exception to be thrown
} catch(Exception $e) {
//exception handling
}
If you do it like this there is no way to miss any exceptions.
如果你这样做,就没有办法错过任何例外。
Otherwise if you get an exception in a controller code that is stored in App\Http\Controllers, your catch will wait for App\Http\Controllers\Exceptionobject to be thrown.
否则,如果您在App\Http\Controllers 中存储的控制器代码中遇到异常,您的捕获将等待App\Http\Controllers\Exception对象被抛出。