0

Wanted to try out this inversify-express-utils package to save time when writing express code. But now, when using the try-catch block to catch the ValidationError() thrown inside the LoginReqDto should technically be caught by the middleware inside server.setErrorConfig. But this does not happen.

If I throw the same error from inside the controller, then it works as expected. But outside the controller it doesn't which would be a roadblock for further development. If someone has built a centralised error-handler to catch errors anywhere in the app in a Inversify-Express Application, it would be helpful if you can just point me in the right direction. Thanks!

Server Configuration

let container = new Container();
containerLoader(container);

let server = new InversifyExpressServer(container, null, { rootPath: "/api" });

server.setConfig((app) => {
  app.use(bodyParser.urlencoded({
    extended: true
  }));
  app.use(bodyParser.json());
  app.use(helmet());
  app.use(morgan('combined'));
});

server.setErrorConfig((app) => {
  console.log('setting server error config');
  app.use((err, req, res, next) => {
    console.log('Middleware hit');

    if (err) {
      if (err instanceof ApiError) {
        return res.status(err.code).json({ message: err.message });
      }
      return res.status(500).json({ message: err.message });
    }
    next();
  });
});

const port = process.env.PORT || 3000;
let app = server.build();
app.listen(port);
console.log(`Server started on port ${port}`);

mongooseLoader();

exports = module.exports = app;

AuthController

@controller('/auth')
export class AuthController extends BaseHttpController {

    constructor() {
        super();
    }

    @httpPost('/login')
    public login(@request() req: Request, @response() res: Response) {
            const loginReq = LoginReqDto.fromBody(req.body);
            return res.status(200).json(loginReq);
    }

}

LoginReqDto

export class LoginReqDto {
    @IsEmail()
    email: string;

    @MinLength(8)
    password: string;

    public static fromBody(body: Partial<LoginReqDto>): LoginReqDto {
        const dto = new LoginReqDto();
        Object.assign(dto, body);
        validate(dto, { whitelist: true })
            .then(errors => {
                if (errors) {
                    const constraintMessage = Object.values(errors[0].constraints)[0];
                    throw new ValidationError(constraintMessage);
                }
            });
        return dto;
    }
}

Expected Output

{ "message": "password must be longer than or equal to 8 characters" }

Actual Output

VALIDATION_ERROR: password must be longer than or equal to 8 characters
    at D:\Freelancing\KCC\src\dto\auth.dto.ts:18:27
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  code: 400
}
Rudr Thakur
  • 330
  • 3
  • 12

0 Answers0