Skip to content
Justice Tech School

Errors and Error Codes

Wrap risky code in try and catch. Node errors have a code like ENOENT, which is better to test than the message text.

Example
const fs = require('node:fs');
try {
  fs.readFileSync('/no/such/file');
} catch (err) {
  console.log(err.code, err instanceof Error);
}
class AppError extends Error {
  constructor(msg, status) { super(msg); this.status = status; }
}
try { throw new AppError('Bad', 400); } catch (e) { console.log(e.name, e.status); }

Result

ENOENT true
Error 400

Exercise

Catch an error.

try { risky() }  (e) {}

Quiz Test

What does ENOENT mean?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.