javascript try catch 不捕获无效日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15792839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:06:48  来源:igfitidea点击:

try catch does not catch invalid date

javascriptdate

提问by Billy Moon

I am trying to validate a date input, so if it is correct, I handle one way, and if invalid, I handle another...

我正在尝试验证日期输入,所以如果它是正确的,我会以一种方式处理,如果无效,我会处理另一种......

var date, datestring, e;

datestring = "2012-03-222";

try {
  date = new Date(datestring);
  /* Ends up logging `Invalid Date`
  */

  console.log(date);
} catch (_error) {
  e = _error;
  /* Should come here and log `Error: Invalid Date` or the likes
  */

  console.log("Erorr: " + e);
}

I could just check the returned string, and see if it is Invalid Dateor not, but am both surprised that try/catchdoes not work for this scenario, and concerned that there might be other error messages I do not match.

我可以只检查返回的字符串,看看它是否Invalid Date存在,但我很惊讶这try/catch不适用于这种情况,并且担心可能有其他我不匹配的错误消息。

How should I handle this problem?

我应该如何处理这个问题?

回答by Michael Pratt

Date objects do not throw an error if they are invalid. There is a method described in this related questionthat will determine if a date is valid.

如果日期对象无效,则它们不会引发错误。这个相关问题中描述一种方法来确定日期是否有效。