Error Handling
try/catch/finally, throwing and creating custom errors, and handling errors in async code.
try / catch / finally
trycode that might throw.catchruns only if something insidetrythrew. Receives the thrown value (usually anError).finallyalways runs, whether or not an error occurred, and even iftry/catchreturn early. Useful for cleanup (closing a connection, hiding a loading spinner).
The Error object
throw can technically throw any value, but throwing an Error (or subclass) is standard practice, since it captures a stack trace:
Built-in error subtypes include TypeError, RangeError, ReferenceError, and SyntaxError each thrown automatically by the engine in specific situations (e.g. calling a non-function throws TypeError).
Custom error classes
Extending Error lets you create domain-specific errors that carry extra information and can be distinguished with instanceof:
Rethrowing
Sometimes you only want to handle a specific error and let everything else propagate up to a caller who knows what to do with it:
Errors in async code
try/catch works around await just like synchronous code:
For plain Promises (without async/await), use .catch():
An unhandled rejection (no .catch() and not inside a try/await) won't crash Node by default but will log a warning always handle rejections explicitly.