简体   繁体   English

try catch 没有得到 date-fns parseISO 错误

[英]try catch doesn't get date-fns parseISO error

there seems a simple mistake by me, I wrote this code to get a formatted date but if date dosn't have correct string to convert, class should catch the error but it doesn't work and an error is shown in console !我似乎有一个简单的错误,我编写了这段代码来获取格式化的日期,但如果日期没有正确的字符串来转换,class 应该会捕获错误,但它不起作用并且控制台中显示错误!

import {format,parseISO} from 'date-fns';

class DateFormats {
  // class methods
  constructor(date) { 
    try{
      this.parsedDate = parseISO(date);      
    }
    catch(e){
      this.parsedDate = new Date();
      console.log('catch Error')
    }
   }
 
   get MMM_d_YYYY() {
     return format(this.parsedDate, "MMM d,yyyy")
    }
 
}
 

const wrongDate='2020-*12-20T04:18:21.471275';

console.log(new DateFormats(wrongDate).MMM_d_YYYY);

error in console:控制台中的错误:

RangeError: Invalid time value

any idea?任何想法?

try..catch should only be used as a last resort so should only be used when there's no other option. try..catch只能作为最后的手段使用,所以只能在没有其他选择的情况下使用。

If a function requires arguments of a particular type, then check before calling it, don't just use try..catch and deal with errors afterward.如果 function 需要特定类型的 arguments,那么在调用它之前进行检查,不要只使用try..catch并在之后处理错误。 In this case, the date-fns parseISO function requires a string to avoid a typeError, so ensure it's called with a string or perhaps return undefined or similar value.在这种情况下,date- fns parseISO function 需要一个字符串以避免 typeError,因此请确保使用字符串调用它,或者可能返回未定义或类似的值。 Then the caller can check the response and deal with it.然后调用者可以检查响应并进行处理。

In this case, if the catch block is executed, then:在这种情况下,如果执行了catch块,那么:

this.parsedDate = 'error';

is executed, so when MMM_d_YYYY is accessed/called it calls format on a string when it's expecting a Date object, so date-fns throws an error.被执行,因此当MMM_d_YYYY被访问/调用时,它在字符串上调用format时,它需要一个日期 object,所以 date-fns 会抛出一个错误。

Avoid both errors by checking before calling the functions, not catching errors afterward.通过在调用函数之前进行检查来避免这两个错误,而不是在之后捕获错误。

If you start using try..catch to handle inappropriate input, you force the caller to also use try..catch , so it starts to propagate through your code.如果您开始使用try..catch来处理不适当的输入,则会强制调用者也使用try..catch ,因此它开始在您的代码中传播。 By handling incorrect input (eg by simply returning an Invalid Date), then the caller can check the return value using an if block and deal with "errors" that way, which is much more economical that try..catch .通过处理不正确的输入(例如通过简单地返回无效日期),调用者可以使用if块检查返回值并以这种方式处理“错误”,这比try..catch更经济。

It's also nice to provide a default where no argument is passed, in this case the current date and time seems appropriate, so:在不传递参数的情况下提供默认值也很好,在这种情况下,当前日期和时间似乎合适,所以:

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)));

The above can be run at npm.runkit以上可以运行在npm.runkit

When You passing the wrong date it is going to catch.当您通过错误的日期时,它会抓住。 At correct place but in cache you are passing the string "error" in the variable this.parsedDate and when you are calling gettter MMM_d_YYYY what getter is trying to compile is在正确的位置但在缓存中,您在变量 this.parsedDate 中传递字符串“error”,当您调用 gettter MMM_d_YYYY时,getter 试图编译的是

//Value of this.parsedDate which is 'error' because of catch
return format('error', "MMM d,yyyy")

This function is throwing an error.这个 function 抛出一个错误。 because 'error' string can not be formattable.因为“错误”字符串不能格式化。

import {format,parseISO} from 'date-fns';

class DateFormats {
  // class methods
  constructor(date) { 
    try{

      this.parsedDate= parseISO(date);
    }
    catch(e){
      this.parsedDate=parseISO(new Date());
      console.log(this.parsedDate)
    }
   }
 
   get MMM_d_YYYY() {
     return format(this.parsedDate, "MMM d,yyyy")
    }
 
}
 

const wrongDate='2020-12-20T04:18:21.471275';

console.log(new DateFormats(wrongDate).MMM_d_YYYY);

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

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