How to properly catch PHP exceptions (Laravel 5.1)(如何正确捕获 PHP 异常 (Laravel 5.1))
问题描述
我有一些代码可以进行数据库调用和网络请求,我将它封装在 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.
这篇关于如何正确捕获 PHP 异常 (Laravel 5.1)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何正确捕获 PHP 异常 (Laravel 5.1)
基础教程推荐
- PHP 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- HTTP 与 FTP 上传 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01