0

I have a custom general error response and it will run when execute return next(error), but it's not working , it threw an error to the console. Please help me and give me an explanation for this.

useErrorHandler.ts: This is my custom error response extending Error

import { Request, Response } from 'express';

export class ErrorResponse extends Error {
  public statusCode: number;

  constructor(message: string, statusCode: number) {
    super(message);
    this.statusCode = statusCode;
  }
}

const handleError = (err: any, req: Request, res: Response) => {
  res.status(err.statusCode || 500).json({
    success: false,
    error: err.message || 'Internal Server Error',
  });
};

export default handleError;

category.controller.ts: This is my controller, i tried to give an error

import { NextFunction, Request, Response } from 'express';
import { createCategory } from '../services/category.service';
import { ErrorResponse } from '../middlewares/error';

export const handleCreateCategory = async (
  req: Request,
  res: Response,
  next: NextFunction
) => {
  // const category = await createCategory(req.body);
  // return res.status(200).send(category);
  return next(new ErrorResponse('cccca 3000', 401));
};

app.ts: this is my main file, it contains routes, headers, middlewares, etc.

import express, { Express, Response, Request } from 'express';
import {
  authRouter,
  productRouter,
  categoryRouter,
  cartRouter,
} from './routes';
import { useErrorHandler } from './middlewares';

class App {
  public express: Express;
  private readonly ENDPOINT: string;

  constructor() {
    this.express = express();
    this.ENDPOINT = '/api/v1';
    this.setHeaders();
    this.setMiddlewares();
    this.mountRoutes();
  }

  private setHeaders(): void {}

  private setMiddlewares(): void {
    this.express.use(express.json());
    this.express.use(express.urlencoded());
  }

  private mountRoutes(): void {
    this.express.use(`${this.ENDPOINT}/auth`, authRouter);
    this.express.use(`${this.ENDPOINT}/product`, productRouter);
    this.express.use(`${this.ENDPOINT}/category`, categoryRouter);
    this.express.use(`${this.ENDPOINT}/cart`, cartRouter);

    //handle err
    this.express.use(useErrorHandler);
  }
}

export default new App().express;

Using Postman to test the error response

2
  • 1
    The handleError function must have 4 arguments that is how express recognise it as an error handler. Docs ... error-handling functions have four arguments instead of three: (err, req, res, next). Commented Sep 3, 2021 at 6:04
  • @Molda i solved it, thank you Commented Sep 3, 2021 at 6:09

1 Answer 1

1

Your error-handler middleware should always have 4 arguments. That's how Express knows it is an error-handler method.

If you write your handleError function like the code below it will work.

const handleError = (err: any, req: Request, res: Response, next: NextFunction) => {
  ...
};

You can read more about it in the official Express Docs.
https://expressjs.com/en/guide/error-handling.html

Refer to the section Writing error handlers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.