Custom errors

suggest change

Creating custom error classes in Node.js allows your application to distinguish between operational failures (e.g., validation failed, record not found) and programmer bugs (e.g., TypeError, syntax errors). Custom errors can encapsulate HTTP status codes, structured validation errors, and custom diagnostic codes while maintaining clean stack traces.


1. Creating a Basic Custom Error Class

In modern JavaScript (ES6+), custom errors inherit from the built-in Error class:

class ApplicationError extends Error {
  constructor(message, options) {
    super(message, options);
    
    // Explicitly set the name property to match the class name
    this.name = this.constructor.name;

    // V8-specific: maintains proper stack trace excluding this constructor call
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, this.constructor);
    }
  }
}

class NotFoundError extends ApplicationError {
  constructor(resource = 'Resource', id = '') {
    const detail = id ? ` with ID "${id}"` : '';
    super(`${resource}${detail} not found.`);
    this.statusCode = 404;
    this.code = 'ERR_NOT_FOUND';
  }
}

// Usage
try {
  throw new NotFoundError('User', 'usr_9981');
} catch (err) {
  if (err instanceof NotFoundError) {
    console.log(`[${err.code}] Status: ${err.statusCode} - ${err.message}`);
  } else {
    console.error('Unexpected error:', err);
  }
}

2. Error Chaining with cause (ES2022 / Node.js 16.9+)

Modern JavaScript supports error chaining via the cause option. This allows you to catch low-level system or network errors and re-throw high-level domain errors without losing the original root cause:

import fs from 'node:fs/promises';

class ConfigLoadError extends ApplicationError {
  constructor(filePath, options) {
    super(`Failed to load configuration file at "${filePath}"`, options);
    this.code = 'ERR_CONFIG_LOAD';
  }
}

async function loadConfig(path) {
  try {
    const raw = await fs.readFile(path, 'utf8');
    return JSON.parse(raw);
  } catch (err) {
    // Chain original error as 'cause'
    throw new ConfigLoadError(path, { cause: err });
  }
}

try {
  await loadConfig('./missing.json');
} catch (err) {
  console.error(err.message);
  console.error('Root cause:', err.cause?.message);
}

When printed with console.error(err), Node.js automatically displays the full chain of errors and stack traces (abbreviated):

ConfigLoadError: Failed to load configuration file at "./missing.json"
    at loadConfig (file:///app.mjs:16:11) {
  code: 'ERR_CONFIG_LOAD',
  [cause]: Error: ENOENT: no such file or directory, open './missing.json'
      at async open (node:internal/fs/promises:...)
      at async loadConfig (file:///app.mjs:12:17) {
    errno: -2,
    code: 'ENOENT',
    syscall: 'open',
    path: './missing.json'
  }
}

3. Structured Validation Error with Details

For input validation (e.g., form validation, JSON schema), attach structured violation details:

class ValidationError extends ApplicationError {
  constructor(message, details = []) {
    super(message);
    this.statusCode = 400;
    this.code = 'ERR_VALIDATION';
    this.details = details; // Array of field validation errors
  }

  toJSON() {
    return {
      error: {
        code: this.code,
        message: this.message,
        details: this.details
      }
    };
  }
}

// Throwing structured error
function validateUserRegistration(data) {
  const issues = [];
  if (!data.email || !data.email.includes('@')) {
    issues.push({ field: 'email', message: 'Must be a valid email address' });
  }
  if (!data.password || data.password.length < 8) {
    issues.push({ field: 'password', message: 'Password must be at least 8 characters' });
  }

  if (issues.length > 0) {
    throw new ValidationError('User registration validation failed', issues);
  }
}

4. Centralized Express.js Error Handling Middleware

Custom error classes integrate cleanly with Express error handling:

import express from 'express';

const app = express();

// Global Express error handler
app.use((err, req, res, next) => {
  // If the error is an operational ApplicationError, respond with custom status and payload
  if (err instanceof ApplicationError) {
    const status = err.statusCode || 500;
    return res.status(status).json({
      error: {
        code: err.code || 'ERR_INTERNAL',
        message: err.message,
        details: err.details || null
      }
    });
  }

  // Unhandled / unexpected programming errors (hide internal stacks in production)
  console.error('Unhandled internal crash:', err);
  res.status(500).json({
    error: {
      code: 'ERR_INTERNAL_SERVER_ERROR',
      message: 'An unexpected internal error occurred.'
    }
  });
});

5. Summary and Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents