Skip to content

Enhancement: [only-throw-error] allow re-throwing a caught error #10376

@ronami

Description

@ronami

Before You File a Proposal Please Confirm You Have Done The Following...

My proposal is suitable for this project

  • I believe my proposal would be useful to the broader TypeScript community (meaning it is not a niche proposal).

Link to the rule's documentation

https://typescript-eslint.io/rules/only-throw-error

Description

only-throw-error (and prefer-promise-reject-errors) disallow throwing non-error values. only-throw-error (and with #10375 prefer-promise-reject-errors too) can be configured to allow throwing unknown and any types in addition to error values.

It's necessary to enable allowThrowingUnknown so re-throwing a cached error is valid (or any in some tsconfig.json configurations):

function test() {
  try {
    // ...
  } catch (error) {
    if (x) {
      throw new Error()
    }

    // this would otherwise fail
    throw error;
  }
}

While configuring allowThrowingUnknown makes the above pass, it allows potentially unsafe throwing of an unknown type:

function foo(): unknown {
  // not necessarily returns an `Error` object
}

function test() {
  // this should fail
  throw foo();
}

This issue proposes an additional option, a stricter form of allowThrowingUnknown, which will allow re-throwing a caught error.

This is relevant both to only-throw-error and prefer-promise-reject-errors.

Fail

function foo(): unknown {
  // not necessarily returns an `Error` object
}

function test() {
  // this should fail
  throw foo();
}

Pass

function test() {
  try {
    // ...
  } catch (error) {
    if (x) {
      throw new Error()
    }

    throw error;
  }
}

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    accepting prsGo ahead, send a pull request that resolves this issueenhancement: plugin rule optionNew rule option for an existing eslint-plugin rulelocked due to agePlease open a new issue if you'd like to say more. See https://typescript-eslint.io/contributing.package: eslint-pluginIssues related to @typescript-eslint/eslint-plugin

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy