javascript - RESTful API 中的 Typescript 自定义错误
问题描述
我有一个从另一个项目中截取的代码,在 RESTful API 中有自定义错误。这一切都很好,直到我将它重构为打字稿。我不明白错误构造器是如何工作的,并且this.response在这个范围内是不知道的。
我如何抛出这个错误
async function authenticate(request, response, next) {
if(!request.body.email) {
return next(new ErrorREST(Errors.BadRequest, "User name missing."));
}
}
错误.js
const Errors = {
BadRequest: {
status: 400,
message: "Request has wrong format."
},
Unauthorized: {
status: 401,
message: "Authentication credentials not valid."
},
Forbidden: {
status: 403,
message: "You're missing permission to execute this request."
}
}
class ErrorREST extends Error {
constructor(type, detail = undefined, ...args) {
super(...args);
if (typeof type !== 'object') {
return new Error("You need to provide the error type.");
}
this.response = type;
if (detail !== undefined) {
this.response.detail = detail;
}
}
}
我还没有找到类似的解决方案。此解决方案通过附加自定义消息提供预定义错误。
解决方案
JavaScript 在您调用它时创建 this.response。所以我创建了这个字段,打字稿就知道了。
第二个问题是,我在处理错误后在 app.ts 中定义了我的路线。
错误.ts
const Errors = {
BadRequest: {
status: 400,
message: "Request has wrong format."
},
Unauthorized: {
status: 401,
message: "Authentication credentials not valid."
},
Forbidden: {
status: 403,
message: "You're missing permission to execute this request."
}
}
export class ErrorREST extends Error {
public response: { status: number; message: string; detail: string };
constructor(error: { status: number, message: string }, detail: string = undefined, ...args) {
super(...args);
this.response = {status: error.status, message: error.message, detail: detail};
}
}
应用程序.ts
this.express.use('/api/users', usersRouter);
this.express.use(function (error, request, response, next) {
logRequest(console.error, request);
console.error("ERROR OCCURRED:");
console.error(error);
if (error == null || error.response == null) {//error is not a custom error
error = new ErrorREST(Errors.InternalServerError);
}
response.status(error.response.status).send(error.response);
将您的错误返回给用户
return next(new ErrorREST(Errors.Unauthorized));
return next(new ErrorREST(Errors.Unauthorized), "Authentication credentials not valid.");
推荐阅读
- swift - Google 日历的随机 EKEventStore 同步问题
- python - 在 Flask 中尝试使用将 *args 作为参数的函数构建 api 时出现内部服务器错误
- arrays - 导出数组中指定的工作表以分隔 pdf
- java - 如何从字符串中删除所有空格?
- firebase - Firebase A/B 测试用户限制
- spring-boot - 设置 thymeleaf 值以锚定标签和空值检查
- python - Windows 7 上的“DNS 服务器不是区域的权威”错误
- python - 我如何将字典取出文件保存在 csv 文件中并将其存储为字典
- autodesk-forge - 锻造设计自动化活动设计 - 处理时间和输出限制
- css - 之前放置在它的父级之后