Custom Error Classes Route instanceof

Model failures as custom error classes and dispatch with instanceof: context rides on instances, prototype chains match subclasses, unknown errors fall through.

JavascriptResilience

Code

javascriptsnippet
37 lines
// 自定义错误类:instanceof 分派按原型链工作,比字符串比对可靠
class ValidationError extends Error {
  constructor(message, field) {
    super(message);
    this.name = 'ValidationError';
    this.field = field;
  }
}

class TimeoutError extends Error {
  constructor(message, ms) {
    super(message);
    this.name = 'TimeoutError';
    this.ms = ms;
  }
}

function parse(value) {
  if (value === null) throw new ValidationError('value required', 'body');
  if (value > 5000) throw new TimeoutError('budget exceeded', value);
  return 'ok';
}

for (const input of [null, 9000, 42]) {
  try {
    console.log(input, '->', parse(input));
  } catch (err) {
    // instanceof 沿原型链匹配:新增错误子类时加分支即可,未知错误走兜底
    if (err instanceof ValidationError) {
      console.log('field', err.field, 'failed:', err.message);
    } else if (err instanceof TimeoutError) {
      console.log('timeout at', err.ms, ':', err.message);
    } else {
      console.log('unknown error:', err.name);
    }
  }
}

Output

Captured from a sandboxed run of this snippet in the build pipeline.

field body failed: value required
timeout at 9000 : budget exceeded
42 -> ok

What the code does

One way to read it: the classes ValidationError and TimeoutError and the function parse, doing all the work.

Repetition is confined to for (const input of [null, 9000, 42]) — the rest of the file is straight-line. A guard precedes the ValidationError and TimeoutError: bad state stops the flow there instead of continuing.

Watch out for

  • The guard value === null short-circuits the flow with an early throw when its condition holds.

Using it

Signature: function parse(value)

Running the file prints labeled results such as field, timeout at, unknown error: — each operation’s effect is visible in the output.

Key statements

if (value === null) throw new ValidationError('value required', 'body');
if (value > 5000) throw new TimeoutError('budget exceeded', value);
return 'ok';

Interactive Tools for This Topic

FAQ

How are precondition violations signaled?
`ValidationError` and `TimeoutError` is raised at the guard (`value === null`), so invalid state never reaches the main logic.
Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. The file defines `parse` at load time.