thiagobustamante / typescript-rest

This is a lightweight annotation-based expressjs extension for typescript.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Using Error inside Preprocessor

jojokoro opened this issue · comments

commented

Hallo

I'm trying to raise friendly JSON errors if my endpoint got invalidation from Preprocessor, but it won't work if I use Promises.

I tried different approaches, but none of them actually returned my error in JSON format (some didn't even returned the message at all)

Example 1 (reject):

function validator(req: express.Request): Promise<any> {
  return new Promise((resolve, reject) => {
    let authToken = req.headers.authorization;

    if (!authToken) {
      return reject(new Errors.ForbiddenError("No user token provided."));
    }
  });
}

Example 2 (resolve):

function validator(req: express.Request): Promise<any> {
  return new Promise((resolve) => {
    let authToken = req.headers.authorization;

    if (!authToken) {
      return resolve(new Errors.ForbiddenError("No user token provided."));
    }
  });
}

Example 3 (throw):

function validator(req: express.Request): Promise<any> {
  return new Promise(() => {
    let authToken = req.headers.authorization;

    if (!authToken) {
      throw new Errors.ForbiddenError("No user token provided.");
    }
  });
}

The answer I would like to receive is:

403 Status
Content-type: application/json
body:
{"message": "No user token provided."}

But instead I receive error 500 in most cases.

Hi @jojokoro ,

It should work for examples 1 and 3 (promise.reject and throw).

We have an working example for it in this test case.

Note that the preProcessor only raises the error. If you want to customize the body of your errors, you can create an Error Handler. Take a llok at this for more info about handling errors.