【问题标题】:Custom error response not working in nodejs written in typescript自定义错误响应在用 typescript 编写的 nodejs 中不起作用
【发布时间】:2021-09-03 18:15:44
【问题描述】:

我有一个自定义的常规错误响应,它会在执行 return next(error) 时运行,但它不起作用,它向控制台抛出了一个错误。请帮助我并给我一个解释。

useErrorHandler.ts:这是我的自定义错误响应扩展 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:这是我的控制器,我试图给出错误

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:这是我的主文件,它包含路由、标头、中间件等。

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

【问题讨论】:

  • handleError 函数必须有 4 个参数,以便快速将其识别为错误处理程序。 Docs ...错误处理函数有四个参数,而不是三个:(err, req, res, next)。
  • @Molda 我解决了,谢谢

标签: node.js typescript express


【解决方案1】:

您的错误处理程序中间件应始终有 4 个参数。这就是 Express 知道它是一个错误处理方法的方式。

如果您像下面的代码那样编写handleError 函数,它将起作用。

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

您可以在官方 Express Docs 中阅读更多相关信息。
https://expressjs.com/en/guide/error-handling.html

请参阅编写错误处理程序部分。

【讨论】:

    猜你喜欢
    • 2019-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 2011-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多