我从另一个项目中截取了一个代码,其中包含RESTful API中的自定义错误。一切正常,直到我将其重构为打字稿为止。我不了解错误构造函数的工作原理,并且在此范围内还不知道 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;
}
}
}
我没有找到类似的解决方案。此解决方案提供了预定义的错误以及其他自定义消息。
答案 0 :(得分:0)
JavaScript在调用它时立即创建this.response。因此,我创建了这个字段,并且typecript知道了。
第二个问题是,我在处理错误后在app.ts中定义了我的路由。
error.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.");