#express custom error handling

2 messages · Page 1 of 1 (latest)

oak needle
#

Hi,

just trying to use an custom error handler in express, but it seems like it is ignored by express.

  ....
  appVars.app.set("trust proxy", ["loopback", "linklocal", "uniquelocal"])
  appVars.app.use(enforceHerokuSSL(serverToBeSecured()))
  appVars.app.use(compression())
  appVars.app.use(bodyParser.json({ type: ["application/vnd.api+json", "application/json"] }))
  appVars.app.use(jsonAPIErrorHandler)
  ....

   export function jsonAPIErrorHandler(
  err: Error,
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) {
  if (err instanceof APIError) {
    res.contentType(jsonAPIContentType)
    res.statusCode = err.statusCode
    res.send(err.cause)
  } else {
    next(err)
  }
}

Errors are dealt with the express default error handler instead of my preferred one. Within the route async handler I call the next(err) function, e.g.

export function getResource(typeId: string) {
  return async (req: express.Request, res: express.Response, next: express.NextFunction) => {
...

    const record = await getSingle(qp, id)
    if (record === null) {
      next(new IDUnknownError(id))
      return
    }

I am somehow not able to step into the next() function with the debugger. Is my signature for jsonAPIERrorHandler wrong?

Thanks

cloud epoch
#

@oak needle This doesn't seem like a TS-specific problem, but if I remember correctly Express error handlers should come last in the list of app.use callbacks so that next() will actually fall back to them.