【发布时间】:2022-09-28 17:38:01
【问题描述】:
我是 Express 的新手,我正在尝试在顶层应用一些错误处理。
在我的控制器文件中,我有一个控制器来获取所有游览。
exports.getAllTours = async (req: Request, res: Response) => {
//Execute query
const features = new APIFeatures(Tour.find(), req.query)
.filter()
.sort()
.limitFields()
.paginate();
// Endpoint: http://localhost:8000/api/v1/tours
// Enter a wrong URL here will not even trigger the console.log function.
// But I want to throw the error right here, not in the app.all(\'*\')
console.log(\"features\", features);
if (!features) {
throw new NotFoundError(\"Tours Not Found\");
}
//same problem here.
const tours = await features.query;
console.log(\"tours\", tours.length);
if (!tours) {
throw new NotFoundError(\"Tours Not Found\");
}
res.status(200).json({
status: \"success\",
result: tours.length,
data: {
tours,
},
});
};
我有一个像这样扩展 Error 类的 CustomError 类。
const httpStatusCode = require(\"./httpStatusCode\");
class CustomError extends Error {
constructor(message: string, statusCode: number, description: string) {
super(description);
//Object.setPrototypeOf(this, new.target.prototype);
this.message = message;
this.statusCode = statusCode;
}
}
module.exports = CustomError;
class NotFoundError extends CustomError {
constructor(message, statusCode) {
super(message, statusCode);
this.message = message;
this.statusCode = httpStatusCode.NOT_FOUND;
}
}
module.exports = NotFoundError;
还有一个错误处理中间件:
import { NextFunction, Request, Response, ErrorRequestHandler } from \"express\";
module.exports = (
err: Error,
req: Request,
res: Response,
next: NextFunction
) => {
err.statusCode = err.statusCode || 500;
err.status = err.status || \"error\";
res.status(err.statusCode).json({
status: err.status,
message: err.message,
});
};
最后,我使用应用程序中的 errorHandler 中间件来捕获所有错误。 但是,问题是 getAllTours 控制器中的所有错误都不会被抛出,而是会在 app.all() 中抛出:
app.use(\"/api/v1/tours\", tourRouter);
app.all(\"*\", (req: Request, res: Response) => {
throw new NotFoundError(\"Page Not Found\");
//next(new AppError(`Can\'t find ${req.originalUrl} on this server`, 404));
});
app.use(errorHandler);
我知道由于端点已更改并在 app.all() 中抛出是有意义的。但是如何在 getAllTours 控制器中手动抛出错误? 我使用 express-async-error 所以我可以在异步函数中使用 throw 关键字。
-
\"在此处输入错误的 URL 甚至不会触发 console.log 功能\".你是什么意思?什么是“错误的 URL”?如果您使用的 URL 与路由不匹配,则不会调用处理程序根本.
tourRouter是什么,getAllTours被调用的是哪条路由?您的问题很可能不在于您的错误处理,而在于您的路线处理。
标签: mongodb express asynchronous mongoose error-handling