Skip to content

Improve catch with automatic instanceof checks #46690

Closed
@pickypg

Description

@pickypg

Suggestion

The recent change that, by default, makes catch variables as unknown (#41016) was an unexpected breaking change.

While writing some code to effectively workaround the change, I found myself writing a lot of duplicative, generic code similar to the example. In addition to err: unknown being the default behavior, I think that Typescript could add some syntax sugar to simplify code blocks for types that support instanceof checks similar to what Java and C# do:

try {
  invokeSomething();
} catch (err: Error | HttpError) {
  console.error(err.message);
} catch (err: OtherType) {
  console.error(err.otherTypeProperty);
} catch (err: unknown) {
  // good luck
  throw err;
}

There are obviously legacy codebases that throw strings and other silly "error" types, but the vast majority could be pushed into using structured Error types with what amounts to syntax sugar. The emitted JS code could be

try {
  invokeSomething();
} catch (err) {
  if (err instanceof Error || err instanceof HttpError) {
    console.error(err.message);
  } else if (err instance OtherType) {
    console.error(err.otherTypeProperty);
  } else {
    // good luck
    throw err;
  }
}

with the err being rethrown automatically if there is no matching catch clause (e.g., the developer never specifies err: unknown).

Bonus points if there was an is functional way to do it for non-instanceof types (for codebases that use canonically typed Error objects and, ideally, a built-in version of that that automatically matches to err: Error). C# effectively supports this notion as an "exception filter".

🔍 Search Terms

catch, unknown, instanceof, Error

Relates to #20024, #42596

✅ Viability Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript/JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
  • This feature would agree with the rest of TypeScript's Design Goals.

⭐ Suggestion

Add Typescript syntax sugar to consistently simplify unknown error type handling.

📃 Motivating Example

No more repetitive code checks for consistently typed codebases for errors! Less errors in your errors!

💻 Use Cases

Stop requiring boilerplate code for every error that will regularly lead to silently ignored errors (including in the example for err:unknown itself).

Metadata

Metadata

Assignees

No one assigned

    Labels

    DuplicateAn existing issue was already created

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions