首页 > 解决方案 > 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;
    }
  }
}

我还没有找到类似的解决方案。此解决方案通过附加自定义消息提供预定义错误。

标签: javascriptnode.jstypescriptresterror-handling

解决方案


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.");

失眠症中的自定义 RestError


推荐阅读