苗条的忽略 try catch 块

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 Fatal error: Call to a member function format() on a non-object

如果提供的时间字符串无效,

DateTime::createFromFormat 不会抛出异常,但会 return 布尔值 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方法。