gpt4 book ai didi

php - Slim 忽略 try catch block

转载 作者:行者123 更新时间:2023-12-03 07:54:06 24 4
gpt4 key购买 nike

我正在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com