在express中使用错误类处理全局错误处理时出现错误

问题描述 投票:0回答:1

我是一名表达新手,在使用错误和中间件的自定义类处理错误时遇到一个错误。

app.error.ts

export class AppError extends Error {
  statusCode: number;
  constructor(message: string, statusCode: number) {
    super(message);
    this.statusCode = statusCode;

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

下面是我使用这个类的控制器的代码

export const chat = async (req: Request, res: Response, next: NextFunction) => {
  const { prompt } = req.body;
  if (!prompt) 
      {
         // Here I am using this AppError class and getting an error which is given below.
         return next(new AppError("Prompt is required", 400));
      }

  try {
    // Here are some asynchronous tasks...

    const responseText = 'Response Text';

    const response: IResponse<string> = {
      success: true,
      data: responseText,
    };

    return sendResponse(res, response, HttpStatus.OK);
  } catch (error: any) {
    // I tried getting an error in catch also but the same issue occurs
    return next(new AppError(error.message, 500));
  }
};

我在评论过的地方遇到错误,

error

Error: Prompt is required
    at E:\Projects\vibe-ai\vibe-ai-backend\src\controllers\chat.controller.ts:11:28
    at Generator.next (<anonymous>)
    at E:\Projects\vibe-ai\vibe-ai-backend\src\controllers\chat.controller.ts:8:71
    at new Promise (<anonymous>)
    at __awaiter (E:\Projects\vibe-ai\vibe-ai-backend\src\controllers\chat.controller.ts:4:12)
    at chat (E:\Projects\vibe-ai\vibe-ai-backend\src\controllers\chat.controller.ts:9:79)
    at Layer.handle [as handle_request] (E:\Projects\vibe-ai\vibe-ai-backend\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\Projects\vibe-ai\vibe-ai-backend\node_modules\express\lib\router\route.js:149:13)
    at Route.dispatch (E:\Projects\vibe-ai\vibe-ai-backend\node_modules\express\lib\router\route.js:119:3)
    at Layer.handle [as handle_request] (E:\Projects\vibe-ai\vibe-ai-backend\node_modules\express\lib\router\layer.js:95:5)

我在主应用程序中像这样使用了

error middleware

import express, { Request, Response, NextFunction } from "express";
import { config } from "dotenv";
import HttpStatus from "http-status-codes";

config();
import { errorMiddleware } from "./src/middlewares";
import { chatRouter } from "./src/routes";
import { AppError } from "./src/utils";

const app = express();
const PORT = process.env.PORT || 6050;

app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.use(here route to the controller);

app.all("*", (req: Request, res: Response, next: NextFunction) => {
  return next(new AppError("Route not found", HttpStatus.NOT_FOUND));
});

app.use(errorMiddleware);

app.listen(PORT, () =>
  console.log(`App is listening at port http://localhost:${PORT}`)
);

错误.middleware.ts

const errorMiddleware = (err: AppError, req: Request, res: Response) => {
  err.statusCode = err.statusCode || 500;
  err.message = err.message || SystemConstants.WENT_WRONG;

  const response: IResponse<undefined> = {
    success: false,
    message: err.message,
    stack: err.stack,
  };

  return res.status(err.statusCode).json(response);
};

我尝试过... 我尝试在任何地方放置一些控制台,但在控制器发生错误后,它不会到达中间件。尽管我尝试将控制台放入

AppError
并在那里获取日志。 另外,我尝试使用
throw new AppError()
但后来我知道它在异步任务中不起作用。

如有任何帮助,我们将不胜感激,提前致谢。

node.js express error-handling middleware
1个回答
0
投票

最近,我知道

error middleware
应该具有所有四个
parameters
error
req
res
next
。 我尝试在
params
中使用全部四个,并且成功了......

错误.middleware.ts

const errorMiddleware = (err: AppError, req: Request, res: Response, next: NextFunction) => {
  err.statusCode = err.statusCode || 500;
  err.message = err.message || SystemConstants.WENT_WRONG;

  const response: IResponse<undefined> = {
    success: false,
    message: err.message,
    stack: err.stack,
  };

  return res.status(err.statusCode).json(response);
};
© www.soinside.com 2019 - 2024. All rights reserved.