Home > Net >  Property 'message' does not exist on type 'ErrorRequestHandler<ParamsDictionary, a
Property 'message' does not exist on type 'ErrorRequestHandler<ParamsDictionary, a

Time:11-18

Hello I created a custom error middleware handler in my node typescript app

and getting an error that message does not exist on type ErrorRquestHandler

const errorHandler = (
  err: ErrorRequestHandler, 
  _req: Request, 
  res: Response, 
  _next: NextFunction
) => {
  const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
  res.status(statusCode);
  res.json({
    message: err.message,
    stack: err.stack
  })
}

I've tried uncommenting "typeRoots" and "types" in my tsconfig.json file and still same error.

What is causing this error? Thanks

CodePudding user response:

It looks like you have an error handler that is declared correctly but the type of the err parameter is wrong, instead, the const errorHandler itself should be typed with ErrorRequestHandler so the parameters are inferred.

The type ErrorRequestHandler is defined as follows in DefinitelyTyped:

export type ErrorRequestHandler<
  P = ParamsDictionary,
  ResBody = any,
  ReqBody = any,
  ReqQuery = ParsedQs,
  Locals extends Record<string, any> = Record<string, any>
> = (
  err: any,
  req: Request<P, ResBody, ReqBody, ReqQuery, Locals>,
  res: Response<ResBody, Locals>,
  next: NextFunction,
) => void;

Suggesting that your code should look as follows:

const errorHandler: ErrorRequestHandler = (
  err, 
  _req, 
  res, 
  _next
) => {
  const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
  res.status(statusCode);
  res.json({
    message: err.message,
    stack: err.stack
  })
}

Note that change to const errorHandler to be typed with ErrorRequestHandler meaning you can drop the explicitly typed parameters on the function (unless you have the tsconfig option enabled that requires them). Do note that now err is typed as err: any thanks to ErrorRequestHandler, you should probably test it to ensure it's an error first before using err.message as its also not guaranteed to be a type of Error. The compiler will allow it however as it's typed as any, to be safe I would recommend you test explicitly for errors using the built-in node utility api before making use of properties.

if (isNativeError(err)) {
  // use err.message
} else {
  // handle unexpected error
  // or send generic unknown error response
}
  • Related