Skip to content

Commit 2bdba2a

Browse files
committed
feat: have the handler implement ErrorRequestHandler
so that it can also handle any caught exception and intercept calls to `next(err)` fixes #7
1 parent 31869b0 commit 2bdba2a

File tree

1 file changed

+18
-31
lines changed

1 file changed

+18
-31
lines changed

src/HttpProblemResponse.ts

+18-31
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,27 @@
1-
import express, { Send } from 'express'
1+
import express from 'express'
22
import { NextFunction } from 'connect'
3-
import { Handler } from 'express-serve-static-core'
4-
import { StatusCodeErrorMapper, IMappingStrategy, ErrorStatusCodes } from 'http-problem-details-mapper'
3+
import { ErrorRequestHandler } from 'express-serve-static-core'
4+
import { IMappingStrategy } from 'http-problem-details-mapper'
55

66
class HttpProblemResponseOptions {
77
public strategy: IMappingStrategy;
88
}
99

10-
function HttpProblemResponse (options: HttpProblemResponseOptions): Handler {
11-
return function HttpProblemDetailsMiddleware (request: express.Request,
12-
response: express.Response, next: NextFunction): void {
13-
const temp = response.send
14-
const strategy = options.strategy
15-
16-
response.send = function (body): void {
17-
let problem = null
18-
let isErrorInstance = body instanceof Error
19-
20-
if (body && isErrorInstance) {
21-
problem = strategy.map(body)
22-
response.statusCode = problem.status
23-
}
24-
25-
if (!body && ErrorStatusCodes.includes(response.statusCode)) {
26-
problem = StatusCodeErrorMapper.mapStatusCode(response.statusCode)
27-
}
28-
29-
if (problem) {
30-
response.setHeader('Content-Type', 'application/problem+json')
31-
temp.apply(this, [JSON.stringify(problem)])
32-
} else {
33-
temp.apply(this, [body])
34-
}
35-
} as Send
36-
37-
return next()
10+
function HttpProblemResponse (options: HttpProblemResponseOptions): ErrorRequestHandler {
11+
const { strategy } = options
12+
13+
return function HttpProblemDetailsMiddleware (error: Error,
14+
request: express.Request,
15+
response: express.Response,
16+
next: NextFunction): void { // eslint-disable-line @typescript-eslint/no-unused-vars
17+
let problem = strategy.map(error)
18+
if (!problem.detail && error.message) {
19+
problem.detail = error.message
20+
}
21+
22+
response.statusCode = problem.status
23+
response.setHeader('Content-Type', 'application/problem+json')
24+
response.send(JSON.stringify(problem))
3825
}
3926
}
4027

0 commit comments

Comments
 (0)