- Notifications
You must be signed in to change notification settings - Fork 5
Closed
Description
Current
Express has a built-in way for returning errors from any middleware with the next(error) call. It appears that errors returned this way do not get converted into problem+json because the handler is an ordinary middleware callback.
Desired
Any error returned in the standard way should be intercepted and converted into a mapped problem document.
Proposal
I think that following best practices of express, the 4-parameter error callback could be used instead. Thus the code can actually be simplified. Here's my implementation:
import { IMappingStrategy } from 'http-problem-details-mapper' class HttpProblemResponseOptions { public strategy: IMappingStrategy; } export function HttpProblemResponse (options: HttpProblemResponseOptions) { const { strategy } = options return (err, req, res, next) => { let problem = strategy.map(err) res.statusCode = problem.status res.setHeader('Content-Type', 'application/problem+json') res.send(JSON.stringify(problem)) } }The only difference is that it must be the last app.use call when setting up express
const server = express() -server.use(HttpProblemResponse({strategy})) server.get('/', async (req: express.Request, res: express.Response): Promise<any> => { return res.send(new NotFoundError({type: 'customer', id: '123' })) }) +server.use(HttpProblemResponse({strategy}))Metadata
Metadata
Assignees
Labels
No labels