freecoding.school100% FREE · NO SIGNUP
Closure CavesISSUE #37 of 61

errors · throwing · custom error classes

LambdaVSThe Mutator
Lambda saysThrow errors with throw; create meaningful ones by extending the Error class.

throw new Error("message") signals a problem and unwinds to the nearest catch. Throw Error objects (not strings) so you get a stack trace. Define custom types by extending Error (class ValidationError extends Error) so callers can catch and branch on the kind of failure.

Power-ups you unlock

The Mutator attacks — common mistakes

Boss battleDefine a custom error class and throw it, then catch and read its name.

Example code

<!doctype html><html><head><meta charset="utf-8"></head>
<body style="background:#06040d;color:#e6e0ff;font-family:monospace;padding:20px"><pre id="o"></pre>
<script>class ValidationError extends Error{constructor(m){super(m);this.name='ValidationError';}}
try{ throw new ValidationError('bad input'); }catch(e){ document.getElementById('o').textContent=e.name+': '+e.message; }</script></body></html>
▶ Open the interactive comic issue
‹ Errors · Try · Catch · FinallyErrors · Stack Traces ›