JavaScript theorytheory 0/50 · 0%
Errors · medium

36. Error handling and custom errors

Throwing usefully and failing loudly.

Throw `Error` objects, not strings, so you keep a stack. Subclass for typed handling and use `cause` to keep the original.

class RpcError extends Error {
  constructor(msg, opts) { super(msg, opts); this.name = "RpcError"; }
}
throw new RpcError("eth_call failed", { cause: e });

Catch narrowly: swallowing every error hides bugs and makes support impossible.

Check your understanding

  1. 1. Why throw an Error rather than a string?

  2. 2. What does the `cause` option do?

  3. 3. What is wrong with a bare catch-all?