問(wèn)題描述
我有一些代碼可以進(jìn)行數(shù)據(jù)庫(kù)調(diào)用和網(wǎng)絡(luò)請(qǐng)求,我將它封裝在 try/catch 中.問(wèn)題是我永遠(yuǎn)無(wú)法捕獲異常,而且它們似乎不是致命的異常:
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
}
也就是說(shuō),我遇到了這樣的異常:
Namely, I encounter exceptions such as these:
[IlluminateDatabaseQueryException]
[PDOException]
[InvalidArgumentException]
有沒(méi)有辦法捕捉這些異常?我是否需要對(duì)每種可能的異常對(duì)象類型進(jìn)行明確(意味著我必須創(chuàng)建許多嘗試/捕獲),或者是否有推薦的方法來(lái)捕獲非致命異常?
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;
如果您使用一個(gè)類而不提供其命名空間,PHP 會(huì)在當(dāng)前命名空間中查找該類.Exception 類存在于全局命名空間中,因此如果您在某些命名空間代碼中執(zhí)行 try/catch,例如您的控制器或模型,您需要執(zhí)行以下操作:
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
}
如果你這樣做,就不會(huì)錯(cuò)過(guò)任何異常.
If you do it like this there is no way to miss any exceptions.
否則,如果您在存儲(chǔ)在 AppHttpControllers 中的控制器代碼中遇到異常,您的捕獲將等待 AppHttpControllersException 對(duì)象被拋出.
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.
這篇關(guān)于如何正確捕獲 PHP 異常 (Laravel 5.1)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!