如何正确抓取PHP异常(Laravel 5.1) [英] How to properly catch PHP exceptions (Laravel 5.1)

查看:397
本文介绍了如何正确抓取PHP异常(Laravel 5.1)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码可以使数据库调用和网络请求,并将其包裹在一个try / catch中。问题是我永远不会捕捉到异常,而且似乎不是致命的例外:

  try {
//使数据库请求和网络调用
} catch(异常$ e){
// handle exception
}

也就是说,我遇到这样的例外:

  [Illuminate \\ Database\QueryException] 
[PDOException]
[InvalidArgumentException]

是有办法捕捉这些例外?我需要为每个可能类型的异常对象(意思是我必须创建许多try / catch)显式,或者是否有推荐的方法来捕获非致命异常?

解决方案

确保您正确使用命名空间。



如果您在不提供命名空间的情况下使用类,PHP会查找在当前命名空间中的类。 异常类存在于全局命名空间中,因此如果您在某些命名空间代码中尝试/捕获,您的控制器或型号,您需要执行以下操作:

  try {
//导致异常抛出的代码
} catch(\Exception $ e){
//异常处理
}

如果你这样做,没有办法错过任何例外。



否则,如果在存储的控制器代码中收到异常 App \Http\Controllers ,您的catch将等待 App \Http\Controlers\Exception 对象抛出。


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:

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

解决方案

Make sure you're using your namespaces properly.

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.

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\Exception object to be thrown.

这篇关于如何正确抓取PHP异常(Laravel 5.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆