user728630 user728630 - 1 month ago 13x
TypeScript Question

Catch block is not execute in typescript

I have a simple pipe which formats passed parameters to date. If it's an invalid conversion then it throws error. But it never actually throws error to catch block.

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

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;

Why catch block is not executed even when it's an invalid date?


If you pass invalid date to the constructor then it's does not throw an error for all inputs, seems that it depends.
It's being talked about here: Fall-back to implementation-specific date formats, and it links to this "rough outline on how the parsing works".

But it seems that if it does not throw an error then it returns Invalid Date, so you can do this:

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

And this way it will throw an error even in such cases.