Node.js Error Handling
ExampleNode.js
const fs = require("fs");
try {
fs.readFileSync("/definitely/not/here.txt");
} catch (err) {
console.log(err.code, err.syscall);
}
class AppError extends Error {
constructor(message, status) {
super(message);
this.name = "AppError";
this.status = status;
}
}
try {
throw new AppError("User not found", 404);
} catch (err) {
console.log(err instanceof AppError, err.name, err.status, err.message);
}
fs.readFile("/nope.txt", (err, data) => {
console.log("callback error:", err.code, data);
});
process.on("uncaughtException", (e) => console.log("last resort:", e.message));
setTimeout(() => { throw new Error("late failure"); }, 20);Output
ENOENT open true AppError 404 User not found callback error: ENOENT undefined last resort: late failure
In callbacks the error is the first argument. Handle errors where they happen; uncaughtException is only a last resort.
Quick check
In a Node callback, what is the first argument?
Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.
Tip: use the left and right arrow keys to move between lessons.