簡體   English   中英

苗條的忽略嘗試捕獲塊

[英]Slim ignoring try catch block

我正在使用Slim編寫REST API的代碼,遇到一種情況,我需要檢查用戶輸入的日期時間是否有效,因此想出了此代碼

$app->post('/test',  function() use($app)
{
    verifyRequiredParams(array('d_string'));
    $response = array();
    $d_string = $app->request->post('d_string');

    try {
        $datetime = datetime::createfromformat('d M Y H:i:s', $d_string);
        $output = $datetime->format('d-M-Y H:i:s');
    }
    catch (Exception $e) {
        $response["error"] = true;
        $response["message"] = $e->getMessage();
        echoRespnse(400,$response);

    }
    $response["error"] = false;
    $response["message"] = "Converted Date";
    $response['output'] = $output;
    echoRespnse(200,$response);

});

當我輸入有效的日期時間字符串(如11-Dec-2015 12:18時,它工作正常,但如果出於測試目的,我輸入了一些隨機字符串,則它會產生500個內部錯誤,而不是給我任何異常。

為什么忽略了try catch塊???

錯誤信息

PHP致命錯誤:在非對象上調用成員函數format()

如果提供的時間字符串無效,則DateTime::createFromFormat將不會引發異常,但會返回布爾值false。

因此,您實際上並不需要try/catch塊來完成此操作:

$datetime = \DateTime::createFromFormat('d M Y H:i:s', $d_string);
if (false === $datetime) {
    // send your 400 response and exit
}
$output = $datetime->format('d-M-Y H:i:s');

// the rest of the code

如果您確實出於各種原因想要保留try/catch塊,則可以自己引發一個異常並在本地捕獲它:

try {
    $datetime = \DateTime::createFromFormat('d M Y H:i:s', $d_string);
    if (false === $datetime) {
        throw new \Exception('Invalid date.');
    }
    $output = $datetime->format('d-M-Y H:i:s');
} catch (\Exception $e) {
    $response["error"] = true;
    $response["message"] = $e->getMessage();
    echoRespnse(400,$response);
}

但是,在這種情況下,我認為並沒有很好的理由拋出異常以僅在本地捕獲該異常,因此我將采用第一個解決方案。

如果要顯示更詳細的錯誤消息,可以使用DateTime :: getLastErrors方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM