简体   繁体   English

苗条的忽略尝试捕获块

[英]Slim ignoring try catch block

I am using Slim to code a REST API, I have come upon a situation where I need to check if the date time entered by user is valid and thus came up with this code 我正在使用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);

});

It works fine when I enter a valid date time string like 11-Dec-2015 12:18 but if just for testing purpose I enter some random string, it gives 500 internal error instead of giving me any exception. 当我输入有效的日期时间字符串(如11-Dec-2015 12:18时,它工作正常,但如果出于测试目的,我输入了一些随机字符串,则它会产生500个内部错误,而不是给我任何异常。

Why is it ignoring the try catch block??? 为什么忽略了try catch块???

Error Info 错误信息

PHP Fatal error: Call to a member function format() on a non-object PHP致命错误:在非对象上调用成员函数format()

DateTime::createFromFormat will not throw an exception if the provided time string is invalid, but will return a boolean false. 如果提供的时间字符串无效,则DateTime::createFromFormat将不会引发异常,但会返回布尔值false。

So you don't really need a try/catch block to accomplish this: 因此,您实际上并不需要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

If you really want to keep your try/catch block for various reasons, you can throw an exception yourself and catch it locally: 如果您确实出于各种原因想要保留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);
}

But I don't see a really good reason to throw an exception just to catch it locally in this situation, so I would go with first solution. 但是,在这种情况下,我认为并没有很好的理由抛出异常以仅在本地捕获该异常,因此我将采用第一个解决方案。

If you want to show more detailed error messages, you can use DateTime::getLastErrors method. 如果要显示更详细的错误消息,可以使用DateTime :: getLastErrors方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM