問題描述
我有一些代碼可以進行數據庫調用和網絡請求,我將它封裝在 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)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!