简体   繁体   中英

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

$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.

Why is it ignoring the try catch block???

Error Info

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

DateTime::createFromFormat will not throw an exception if the provided time string is invalid, but will return a boolean false.

So you don't really need a try/catch block to accomplish this:

$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 {
    $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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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