Implementing a RESTful API with Advanced Error Handling in Node.js

When building robust RESTful APIs, proper error handling is important for maintaining, debugging, and providing clear feedback to API consumers. In this comprehensive guide, we'll explore how to implement advanced error handling in a Node.js API using Express. Table of Contents Setting Up the Project Custom Error Classes Error Handling Middleware Implementation Examples Testing Error Handling Best Practices Reactjs Template Download Now Setting Up the Project First, let's set up a basic Express project with necessary dependencies: const express = require('express'); const app = express(); app.use(express.json()); const PORT = process.env.PORT || 3000; Custom Error Classes Create a hierarchy of custom error classes to handle different types of errors: // Base error class for operational errors class AppError extends Error { constructor(message, statusCode) { super(message); this.statusCode = statusCode; this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error'; this.isOperational = true; Error.captureStackTrace(this, this.constructor); } } // Specific error classes class ValidationError extends AppError { constructor(message) { super(message, 400); } } class NotFoundError extends AppError { constructor(message) { super(message, 404); } } class UnauthorizedError extends AppError { constructor(message) { super(message, 401); } } Error Handling Middleware Implement a central error handling middleware: // Error handling middleware const errorHandler = (err, req, res, next) => { err.statusCode = err.statusCode || 500; err.status = err.status || 'error'; if (process.env.NODE_ENV === 'development') { res.status(err.statusCode).json({ status: err.status, error: err, message: err.message, stack: err.stack }); } else { // Production error response if (err.isOperational) { res.status(err.statusCode).json({ status: err.status, message: err.message }); } else { // Programming or unknown errors console.error('ERROR

Feb 23, 2025 - 08:24
 0
Implementing a RESTful API with Advanced Error Handling in Node.js

When building robust RESTful APIs, proper error handling is important for maintaining, debugging, and providing clear feedback to API consumers. In this comprehensive guide, we'll explore how to implement advanced error handling in a Node.js API using Express.

Table of Contents

  • Setting Up the Project
  • Custom Error Classes
  • Error Handling Middleware
  • Implementation Examples
  • Testing Error Handling
  • Best Practices

Reactjs Template

reactjs-template

Download Now

Setting Up the Project

First, let's set up a basic Express project with necessary dependencies:

const express = require('express');
const app = express();

app.use(express.json());

const PORT = process.env.PORT || 3000;

Custom Error Classes

Create a hierarchy of custom error classes to handle different types of errors:

// Base error class for operational errors
class AppError extends Error {
    constructor(message, statusCode) {
        super(message);
        this.statusCode = statusCode;
        this.status = `${statusCode}`.startsWith('4') ? 'fail' : 'error';
        this.isOperational = true;

        Error.captureStackTrace(this, this.constructor);
    }
}

// Specific error classes
class ValidationError extends AppError {
    constructor(message) {
        super(message, 400);
    }
}

class NotFoundError extends AppError {
    constructor(message) {
        super(message, 404);
    }
}

class UnauthorizedError extends AppError {
    constructor(message) {
        super(message, 401);
    }
}

Error Handling Middleware

Implement a central error handling middleware:

// Error handling middleware
const errorHandler = (err, req, res, next) => {
    err.statusCode = err.statusCode || 500;
    err.status = err.status || 'error';

    if (process.env.NODE_ENV === 'development') {
        res.status(err.statusCode).json({
            status: err.status,
            error: err,
            message: err.message,
            stack: err.stack
        });
    } else {
        // Production error response
        if (err.isOperational) {
            res.status(err.statusCode).json({
                status: err.status,
                message: err.message
            });
        } else {
            // Programming or unknown errors
            console.error('ERROR