thiagobustamante / typescript-rest

This is a lightweight annotation-based expressjs extension for typescript.
MIT License
525 stars 108 forks source link

@PreProcessor errors not catched by express error middleware #157

Closed mimiz closed 3 years ago

mimiz commented 3 years ago

Hi Guys,

First of all thank you for this project ! I would like to use @PreProcessor to do validation as demonstrated in the documentation.

function validator(req: express.Request): express.Request {
  if (!req.body.userId) {
    throw new ValidationError("userId not present", {details:{path:"userId"}});
  } 
}

@Path('users')
export class UserHandler {

  @Path('email')
  @POST
  @PreProcessor(validator)
  setEmail(body: any) {
    // will have body.userId
  }
}

Also I would like to catch all errors with an express error middleware as shown in this question.

import { HttpError } from 'typescript-rest';
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
  if (err instanceof ValidationError){
    if (res.headersSent) { // important to allow default error handler to close connection if headers already sent
      return next(err)
    }
    res.set("Content-Type", "application/json")
    res.status(err.statusCode)
    res.json(err.details);
  } else {
    next(err);
  }
});

The problem is that the exception thrown in validator is not "catched" by the express middleware.

Did someone find a workaround ? Or have any ideas to manage this ?

Regards

Rémi

mimiz commented 3 years ago

Hi I've found why I had this issue, it was because I did call async method within a constructor ...

Sorry for reporting