Nội dung

In Node.js, there are various ways to handle errors. In this blog, I will show you how to handle them in a very easy way and get rid of all try-catch blocks.

Setup

Let’s assume we have a simple Node.js (Express) server running. Now install npm packages called express-async-errors and http-status-codes.

npm i express-async-errors

express-async-errors is a small package which does most of the heavy lifting. Let’s use this package in the root file, and it should always be at the top.

require('express-async-errors');

const express = require('express');

const app = express();

app.use(express.json());

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`server is listening on port ${port}...`);
});

Custom Error Utility

Let’s create utility functions to throw different errors.

const { StatusCodes } = require("http-status-codes");

class CustomAPIError extends Error {
  constructor(message) {
    super(message);
  }
}

class BadRequestError extends CustomAPIError {
  constructor(message) {
    super(message);
    this.statusCode = StatusCodes.BAD_REQUEST;
  }
}

class ConflictError extends CustomAPIError {
  constructor(message) {
    super(message);
    this.statusCode = StatusCodes.CONFLICT;
  }
}

class NotFoundError extends CustomAPIError {
  constructor(message) {
    super(message);
    this.statusCode = StatusCodes.NOT_FOUND;
  }
}

class UnauthenticatedError extends CustomAPIError {
  constructor(message) {
    super(message);
    this.statusCode = StatusCodes.UNAUTHORIZED;
  }
}

class UnauthorizedError extends CustomAPIError {
  constructor(message) {
    super(message);
    this.statusCode = StatusCodes.FORBIDDEN;
  }
}

module.exports = {CustomAPIError, BadRequestError, ConflictError, NotFoundError, UnauthenticatedError, UnauthorizedError}

Middleware

const { StatusCodes } = require('http-status-codes');

const { CustomAPIError } = require('../errors');

const errorHandlerMiddleware = (err, req, res, next) => {
  const customError = {
    msg: 'Something went wrong, please try again',
    statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
  };

  if (err instanceof CustomAPIError) {
    customError.msg = err.message;
    customError.statusCode = err.statusCode;
  }

  res.status(customError.statusCode).json({ msg: customError.msg });
};

module.exports = errorHandlerMiddleware;

Optional Checks

You can add some optional checks too. I will show some examples for Prisma and Mongoose.

Prisma

const { StatusCodes } = require('http-status-codes');
const { Prisma } = require('@prisma/client');

const { CustomAPIError } = require('../errors');

const errorHandlerMiddleware = (err, req, res, next) => {
  const customError = {
    msg: 'Something went wrong, please try again',
    statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
  };

  if (err instanceof CustomAPIError) {
    customError.msg = err.message;
    customError.statusCode = err.statusCode;
  }

  if (err instanceof Prisma.PrismaClientKnownRequestError) {
      switch (err.code) {
        case 'P2000': {
          const key = err.meta.column_name;
          customError.msg = `${key} is too long`;
          customError.statusCode = StatusCodes.BAD_REQUEST;
          break;
        }
        case 'P2001': {
          customError.msg = 'Not found';
          customError.statusCode = StatusCodes.NOT_FOUND;
          break;
        }
        case 'P2002': {
          const key = err.meta.target[0];
          customError.msg = `Provided ${key} already exists`;
          customError.statusCode = StatusCodes.CONFLICT;
          break;
        }
        case 'P2003': {
          const key = err.meta.field_name;
          customError.msg = `${key} does not exist`;
          customError.statusCode = StatusCodes.NOT_FOUND;
          break;
        }
        case 'P2025': {
          customError.msg = 'No record found to delete';
          customError.statusCode = StatusCodes.NOT_FOUND;
          break;
        }
        default: {
          customError.msg = 'Something went wrong, please try again';
          customError.statusCode = StatusCodes.INTERNAL_SERVER_ERROR;
        }
      }
    }

  res.status(customError.statusCode).json({ msg: customError.msg });
};

module.exports = errorHandlerMiddleware;

Mongoose

const { StatusCodes } = require('http-status-codes');
const mongoose = require('mongoose');

const { CustomAPIError } = require('../errors');

const errorHandlerMiddleware = (err, req, res, next) => {
  const customError = {
    msg: 'Something went wrong, please try again',
    statusCode: StatusCodes.INTERNAL_SERVER_ERROR,
  };

  if (err instanceof CustomAPIError) {
    customError.msg = err.message;
    customError.statusCode = err.statusCode;
  }

  if (err instanceof mongoose.Error.ValidationError) {
     if (err.name === "ValidationError") {
        customError.msg = Object.values(err.errors)
          .map((item) => item.message)
          .join(",");
        customError.statusCode = StatusCodes.BAD_REQUEST;
      }
    
      if (err.code && err.code === 11000) {
        customError.msg = `Duplicate value entered for ${Object.keys(
          err.keyValue
        )} field, please choose another value`;
        customError.statusCode = StatusCodes.BAD_REQUEST;
      }
    
      if (err.name === "CastError") {
        customError.msg = `No match found with id of ${err.value}`;
        customError.statusCode = StatusCodes.NOT_FOUND;
      }
    }

  res.status(customError.statusCode).json({ msg: customError.msg });
};

module.exports = errorHandlerMiddleware;

That’s It

Now use that middleware below all API routes. We don’t have to wrap any async code block inside try-catch. All the errors will be automatically caught by our middleware.

require('express-async-errors');

const express = require('express');

const errorHandlerMiddleware = require('./middleware/error-handler');

const app = express();

app.use(express.json());

/* api routes */
...

app.use(errorHandlerMiddleware);

const port = process.env.PORT || 5000;

app.listen(port, () => {
  console.log(`server is listening on port ${port}...`);
});

Hope that helps! Let me know if you have any further questions or need more clarification!

Anthony Nguyễn

Cây bút chính tại VietnamTutor

Bài viết cùng chuyên mục

Quy trình vibe coding 7 bước: từ ý tưởng đến prototype

Quy trình vibe coding hiệu quả bắt đầu từ giả thuyết kinh doanh, không phải prompt dài. Bài viết hướng dẫn 7 bước từ brief, dữ

Vibe coding cho doanh nghiệp: việc nào nên làm bằng AI?

Vibe coding cho doanh nghiệp hữu ích khi cần thử prototype, dashboard hoặc automation nhỏ. Bài viết giúp bạn phân loại use case theo mức rủi

AI viết code nhanh hơn review: kiểm soát thế nào?

Khi AI viết code nhanh hơn khả năng review của team, doanh nghiệp cần đổi cách kiểm soát chất lượng. Bài viết đưa ra framework thực

Git detached HEAD là gì? Cách thoát an toàn

Bài viết này giải thích detached HEAD trong Git, cách nhận biết trạng thái này và các bước thoát ra an toàn mà không mất code.

Rủi ro vibe coding: 9 lỗi khiến prototype khó vận hành

Bài viết này chỉ ra 9 rủi ro phổ biến khi vibe coding và cách kiểm soát để prototype không biến thành gánh nặng vận hành.

Vibe coding là gì? Cách thử ý tưởng phần mềm bằng AI

Vibe coding giúp chủ doanh nghiệp biến ý tưởng phần mềm thành prototype nhanh hơn bằng AI. Bài viết này chỉ ra khi nào nên thử,

GitHub Actions CI/CD: quy trình deploy website an toàn

Hướng dẫn xây pipeline GitHub Actions CI/CD cho website: build, test, cache dependency, đóng artifact, deploy staging/production và quản lý secret an toàn.

.gitignore không hoạt động: nguyên nhân và cách sửa

Bài viết giúp bạn kiểm tra vì sao .gitignore không hoạt động, sửa lỗi file đã tracked và dùng git check-ignore để debug pattern.

Git push bị rejected: cách sửa non-fast-forward

Bài viết giải thích vì sao git push bị rejected, cách đọc lỗi non-fast-forward và quy trình xử lý an toàn trước khi push lại.

Git reset revert restore: chọn lệnh đúng

Bài viết so sánh git reset, git revert và git restore theo mục đích sử dụng: sửa staging area, khôi phục file, undo commit chưa push

Git commit vào nhánh sai: cách chuyển an toàn

Bài viết hướng dẫn xử lý git commit vào nhánh sai theo từng tình huống: commit chưa push, đã push, nhiều commit liên tiếp hoặc branch

TypeScript cho website doanh nghiệp: API, form và lỗi

TypeScript cho website doanh nghiệp đáng dùng khi bạn cần kiểm soát API contract, form schema, CMS payload và cấu hình môi trường. Bài này giúp