Error Handling and Debugging
What this domain covers
Recognising which built-in error type a bug produces, writing try/catch/finally correctly, creating custom errors, and using the console and stack traces to locate a fault.
Error types
SyntaxError- thrown at parse time; a syntax error in the current file cannot be caught by that file's owntry/catch.ReferenceError- undeclared identifier, or alet/constread before declaration.TypeError- calling a non-function, or reading a property ofundefined/null.RangeError- invalid array length or an invalidtoFixeddigit count.
Every Error carries name, message, and stack.
try / catch / finally
catch receives the thrown value; the binding is optional (catch {}). finally runs whether the block threw, returned, or completed - and a return inside finally silently overrides the earlier return. throw can throw any value, but throwing Error instances keeps stack traces.
Custom errors and async code
Extend Error, call super(message), and set this.name. In async code, an un-awaited rejected promise escapes try/catch; you must await it or attach .catch.
Worked example
function parse(s) {
try { return JSON.parse(s); }
catch (e) { console.log(e.name); return null; }
finally { console.log('done'); }
}
console.log(parse('{bad'));
console.log(parse('{"a":1}'));
Reasoning: the first call throws a SyntaxError from JSON.parse; the catch logs SyntaxError and returns null, but finally prints done before the value leaves the function. The second call returns the object, and finally still prints done.
Traps
- Expecting one
tryaround many statements to tell you which statement failed. - Logging a thrown non-
Errorvalue and assumingmessageexists. - Placing
finallybeforecatch, which is illegal ordering. - Leaving a
debugger;statement in shipped code.