javascript – 在typescript中不执行Catch块

我有一个简单的管道,它将传递的参数格式化为日期格式.如果它是无效转换,则会引发错误.但它从来没有真正抛出一个错误落入catch块.

import {PipeTransform, Pipe} from 'angular2/core';

@Pipe({
    name: 'formatDate'
})

export class FormatDatePipe implements PipeTransform {
    transform(value: string): any {
        let date: string;
        try {
            date = new Date(value).toLocaleDateString();
        }
        catch (Exception) {
            return value;
        }
        finally {            
            return date;
        }        
    }

为什么即使传递无效日期,catch块也不会被执行?

最佳答案 如果您将无效日期传递给构造函数,那么它不会为所有输入抛出错误,这取决于.

你可以在这里阅读:Fall-back to implementation-specific date formats,链接到这个“rough outline on how the parsing works”.

但似乎如果它没有抛出错误然后它返回无效日期,所以你可以这样做:

try {
    date = new Date(value).toLocaleDateString();
    if (date === "Invalid Date") {
        throw new Error(`invalid date value ${ value }`);
    }
}

这种方式即使在这种情况下也会引发错误.

点赞