Typescript: Error in catch clause should be unknown

Created on 3 Aug 2018  路  3Comments  路  Source: microsoft/TypeScript

Search Terms

catch unknown type

Suggestion

Today I had another situation where I would have wanted https://github.com/Microsoft/TypeScript/issues/13219, but a less complex feature that would have prevented the bug as well would have been if the error in catch clauses had the new unknown type instead of any, forcing me to narrow it down before accessing properties.

Ideally this would be the same for the Promise rejection type.

Use Cases

Making error handling more type safe. Currently any prevents type narrowing.

Examples


This is a real world example of a bug:

    let pipeline: Pipeline
    try {
        ;({ body: pipeline } = await buildkiteClient.post('organizations/sourcegraph/pipelines', {
            body: buildkitePipeline,
            json: true,
        }))
    } catch (err) {
        if (
            err.error &&
            Array.isArray(err.error.errors) &&
            err.errors[0] &&
            err.errors[0].field === 'name' &&
            err.errors[0].code === 'already_exists'
        ) {
            console.log(`Buildkite pipeline ${repoName} already exists, skipping creation`)
            pipeline = await buildkiteClient.get(`organizations/sourcegraph/pipelines/${repoName}`)
        } else {
            throw err
        }
    }

Very easy to miss in code review - it should have been err.error.errors. This is an error returned by a real API.

Checklist

My suggestion meets these guidelines:

  • [x] This wouldn't be a breaking change in existing TypeScript / JavaScript code (with a flag)
  • [x] This wouldn't change the runtime behavior of existing JavaScript code
  • [x] This could be implemented without emitting different JS based on the types of the expressions
  • [x] This isn't a runtime feature (e.g. new expression-level syntax)
Awaiting More Feedback Suggestion

Most helpful comment

I want to enable this change by a compiler option. Or want to declare only unknown type like catch (reason: unknow) { }.

All 3 comments

This is only possible if #25720, #10715, #25172, and #21732 are implemented. otherwise it is a massive breaking change.

I'd love to see this as well. I just made a PR to get this for Reacts componentDidCatch (https://github.com/DefinitelyTyped/DefinitelyTyped/pull/30068), because it would have prevented a real world bug in our code and looked for an equivalent issue for the native try/catch.

I want to enable this change by a compiler option. Or want to declare only unknown type like catch (reason: unknow) { }.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

xealot picture xealot  路  150Comments

disshishkov picture disshishkov  路  224Comments

rbuckton picture rbuckton  路  139Comments

OliverJAsh picture OliverJAsh  路  242Comments

rwyborn picture rwyborn  路  210Comments