0

why it can use without new HttpException() then trown a error I saw this method elsewhere,and it is work

Here is HttpException

class HttpException extends Error{
  constructor(public status: number,public message: string){
      super(message);
      this.status=status;
      this.message=message;
  }
}
export default HttpException;

Here is error handler

const errorMiddleware = (error: HttpException, _request: Request, response: Response, next: NextFunction) => {
  const status = error.status || 500;
  const message = error.message || ' something wrong';

  response
    .status(status)
    .send({
      status,
      message
    });
    
  logger.error(error.name);
  logger.error(error.message);
  logger.error(error.stack);

  next(error);
};

user in app.ts

// ...some routers
app.use(errorMiddleware)

api error in postman

{
    "status": 500,
    "message": "User validation failed: username: Error, expected `username` to be unique. Value: `aaa111`"
}
BuzzWoods
  • 11
  • 1
  • What is your exact question? The code is nice formatted, but I can't understand what is the problem :-( – Jorge Fuentes González Aug 16 '21 at 17:20
  • @JorgeFuentesGonzález i not know why it thrown error type is HttpException,not Errro,it is because error that func params type is named HttpException? then throw HttpException type instance? – BuzzWoods Aug 16 '21 at 17:38
  • Because some calls have custom type errors. Is like when you write bad syntax, like `var var a = 123; (double var)`, you get "SyntaxError". – Jorge Fuentes González Aug 17 '21 at 16:15

0 Answers0