Summary - Error handling
- Node.js course
- Intermediate
- Lesson 81/116
- 5 min
Combine Error, try/catch and custom error to write an error class hierarchy.
Summary - Error handling
In this group you learned the core tools of error handling: the Error class, catching with try/catch, custom error classes, Express error middleware and the unhandledRejection event.
You can combine these five tools to build a solid error handling system. For example, you can define a custom error class and catch it with try/catch. This is the basic pattern for handling errors in a controlled way in Node.js apps. Now you will combine all pieces in one piece of code.
Practice Write an AppError class and catch it
Define an AppError class that extends Error. In constructor(message) set super(message) and this.name = "AppError". In try throw new AppError("test"), in catch (e) print console.log(e.name).
Starter code
// Define an AppError class (extends Error)
// In constructor set super and this.name
// Throw in try, print name in catch
// write hereSample solution
class AppError extends Error {
constructor(message) {
super(message);
this.name = "AppError";
}
}
try {
throw new AppError("test");
} catch (e) {
console.log(e.name);
}Expected output
AppError
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each tool to its role
| Term | Meaning |
|---|---|
Error |
Base error class |
try/catch |
Catches errors |
extends |
Derives a class |
error middleware |
Express error handler |
2 Which variable holds the error caught by try/catch?
catch (e)- The e in catch(e) Correct answer
- The name in throw
- A global error
- process.err
Explanation: The e in catch(e) holds the thrown error.
3 Complete the super call
constructor(message) { ____(message); this.name = "AppError"; }
constructor(message) { super(message); this.name = "AppError"; }
Explanation: super(message) calls the parent's constructor.