我从另一个项目中截取了一段代码,其中存在 RESTful API 中的自定义错误。这一切都工作得很好,直到我将其重构为 typescript 。我不明白错误构造器是如何工作的,并且 this.response 在此范围内不知道。
我如何抛出此错误
async function authenticate(request, response, next) {
if(!request.body.email) {
return next(new ErrorREST(Errors.BadRequest, "User name missing."));
}
}
error.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。所以我创建了这个字段并且 typecript 知道它。
第二个问题是,我在错误处理后在 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};
}
}
app.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.");
关于javascript - RESTful API 中的 Typescript 自定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54892347/