php - Slim 忽略 try catch block

标签 php error-handling slim

我正在使用 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 内部错误 而不是给我任何异常(exception)。

为什么忽略 尝试捕获 堵塞???

错误信息

PHP Fatal error: Call to a member function format() on a non-object

最佳答案

DateTime::createFromFormat如果提供的时间字符串无效,则不会抛出异常,但会返回 bool 值 false。

所以你真的不需要 try/catch block 来完成这个:

$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方法。

关于php - Slim 忽略 try catch block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34115491/

相关文章:

php - 为每个版本的 API 使用单独的目录

php - netbeans : cURL error 60 中的 Symfony 项目

javascript - 无法在纯 js 中处理 net::ERR_CONNECTION_REFUSED

php - Composer 未找到类 'Slim\Slim'

php - 超薄 Controller 请求、响应和参数不可用

php - Slim 缺少闭合

php - 如何在 Laravel 5.1 项目中链接外部 CSS 和脚本( Assets )

php - php 中的负后视和贪婪量词

php - Laravel 5.4在 View 中显示错误

c# - 检测到绑定(bind)失败 'Microsoft.Practices.EnterpriseLibrary.Validation'