Пользовательские ошибки машинописи в RESTful API - PullRequest
0 голосов
/ 26 февраля 2019

У меня есть фрагмент кода из другого проекта с пользовательскими ошибками в 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;
    }
  }
}

Я не нашел аналогичного решения.Это решение предоставляет предопределенные ошибки с дополнительными настраиваемыми сообщениями.

1 Ответ

0 голосов
/ 03 марта 2019

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

Custom RestError in Insomnia

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...