如何正确捕获 PHP 异常 (Laravel 5.1)

2021-12-26 00:00:00 exception php laravel laravel-5 eloquent

我有一些代码可以进行数据库调用和网络请求,我将它封装在 try/catch 中.问题是我永远无法捕获异常,而且它们似乎不是致命的异常:

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:

try {
   // make db requests and network calls
} catch (Exception $e) {
   // handle exception
}

也就是说,我遇到了这样的异常:

Namely, I encounter exceptions such as these:

[IlluminateDatabaseQueryException] 
[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?

推荐答案

确保正确使用命名空间,方法是在控制器顶部包含 Exception 类,如下所示:

Make sure you're using your namespaces properly, by including the Exception class at the top of your controller like this:

 Use Exception; 

如果您使用一个类而不提供其命名空间,PHP 会在当前命名空间中查找该类.Exception 类存在于全局命名空间中,因此如果您在某些命名空间代码中执行 try/catch,例如您的控制器或模型,您需要执行以下操作:

If you use a class without providing its namespace, PHP looks for the class in the current namespace. Exception class 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:

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.

否则,如果您在存储在 AppHttpControllers 中的控制器代码中遇到异常,您的捕获将等待 AppHttpControllersException 对象被抛出.

Otherwise if you get an exception in a controller code that is stored in AppHttpControllers, your catch will wait for AppHttpControllersException object to be thrown.

相关文章