|
1 |
| -import express, { Send } from 'express' |
| 1 | +import express from 'express' |
2 | 2 | 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' |
5 | 5 |
|
6 | 6 | class HttpProblemResponseOptions {
|
7 | 7 | public strategy: IMappingStrategy;
|
8 | 8 | }
|
9 | 9 |
|
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)) |
38 | 25 | }
|
39 | 26 | }
|
40 | 27 |
|
|
0 commit comments