Better error handling, and handling of numeric config options

This commit is contained in:
Alan Grainger
2026-07-24 22:15:17 +12:00
parent a1e440c146
commit aa6183a95d
13 changed files with 345 additions and 51 deletions
+27 -1
View File
@@ -1,5 +1,7 @@
import { Response } from 'express-serve-static-core'
import { NextFunction, Request, Response } from 'express-serve-static-core'
import { getConfigOption } from './config/access'
import { respondToInvalidRequest } from './invalidRequestHandler'
import { log } from './utils/log'
/**
* Apply the response headers configured under `ipp.responseHeaders` to the
@@ -12,3 +14,27 @@ export function addResponseHeaders (res: Response): void {
res.set(header, value)
})
}
/**
* Wrap an async route handler so a rejected promise is passed to Express's
* error chain (and on to `errorHandler`).
*/
export function asyncHandler (fn: (req: Request, res: Response, next: NextFunction) => Promise<unknown>) {
return (req: Request, res: Response, next: NextFunction): void => {
fn(req, res, next).catch(next)
}
}
/**
* Terminal Express error middleware. Logs the error server-side, then applies the
* same privacy policy as any other invalid request.
*/
export function errorHandler (err: unknown, req: Request, res: Response, _next: NextFunction): void {
log.error('Error handling ' + req.method + ' ' + req.path + ' - ' +
(err instanceof Error ? (err.stack || err.message) : String(err)))
if (res.headersSent) {
res.end()
return
}
respondToInvalidRequest(res, 404, 'Unhandled error for ' + req.path)
}