Skip to content

No Throw Literal

In JavaScript, you can throw any value, but it's best to throw only Error instances.

ts
// eslint-disable-next-line no-throw-literal
throw 'error' // ✗ avoid
throw new Error('error') // ✓ recommended

INFO

oRPC treats thrown Error instances as best practice by default, as recommended by the JavaScript Standard Style.

Configuration

Customize oRPC's behavior by setting ThrowableError in the Registry:

ts
declare module '@orpc/server' { // or '@orpc/contract', or '@orpc/client'
  interface Registry {
    ThrowableError: Error
  }
}

INFO

Avoid using any or unknown for ThrowableError because doing so prevents the client from inferring typesafe errors. Instead, use null | undefined | {} (equivalent to unknown) for stricter error type inference.

WARNING

If ThrowableError is configured as null | undefined | {}, check isSuccess instead of relying on error:

ts
const { error, data, isSuccess } = await safe(client('input'))

if (!isSuccess) {
  if (isInferableError(error)) {
    // handle typesafe errors
  }

  // handle other errors
}
else {
  // handle success
}

Bonus

If you use ESLint, enable the no-throw-literal rule to enforce throwing only Error instances.

Released under the MIT License.