try..catch 只能作为最后的手段使用,因此只能在没有其他选择的情况下使用。
如果一个函数需要特定类型的参数,那么在调用它之前进行检查,不要只使用 try..catch 并在之后处理错误。在这种情况下,date-fns parseISO 函数需要一个字符串来避免 typeError,因此请确保使用字符串调用它,或者可能返回 undefined 或类似值。然后调用者可以检查响应并进行处理。
在这种情况下,如果 catch 块被执行,那么:
this.parsedDate = 'error';
被执行,因此当 MMM_d_YYYY 被访问/调用时,它在期待 Date 对象时调用字符串上的 format,因此 date-fns 会引发错误。
通过在调用函数之前检查避免这两个错误,而不是在之后捕获错误。
如果你开始使用 try..catch 来处理不适当的输入,你会强制调用者也使用 try..catch,所以它开始在你的代码中传播.通过处理不正确的输入(例如通过简单地返回一个无效日期),调用者可以使用 if 块检查返回值并以这种方式处理“错误”,这比 try..catch.
在不传递参数的情况下提供默认值也很好,在这种情况下,当前日期和时间似乎合适,所以:
let format = require('date-fns/format')
let parseISO = require('date-fns/parseISO')
class DateFormats {
// class methods
// Default is current date and time
constructor(arg = new Date().toISOString()) {
// Ensure arg is a string and let date-fns deal with parsing it
// This might result in an invalid Date, but let the caller
// deal with that
this.parsedDate = parseISO(String(arg));
}
// Return timestamp in MMM d YYYY format or "Invalid Date"
get MMM_d_YYYY() {
// this.parsedDate might be an invalid Date, so check first
// as calling format on an invalid date throws an error
if (isNaN(this.parsedDate)) {
return this.parsedDate.toString(); // Invalid Date
}
// Otherwise, it's a valid Date so use it
return format(this.parsedDate, "MMM d,yyyy")
}
}
// Examples
[void 0, // default, no arg -> Jan 31,2021
'2020-12-20T04:18:21.471275', // valid timestamp -> Dec 20,2020
'fooBar' // invalid timestamp -> Invalid Date
].forEach(arg => console.log(arg + ' -> ' + (arg? new DateFormats(arg).MMM_d_YYYY : new DateFormats().MMM_d_YYYY)));
以上可以在npm.runkit运行