1 | import { jsonSafeParse, normalizeHttpResponse } from '@middy/util';
|
2 | const defaults = {
|
3 | logger: console.error,
|
4 | fallbackMessage: null
|
5 | };
|
6 | const httpErrorHandlerMiddleware = (opts = {})=>{
|
7 | const options = {
|
8 | ...defaults,
|
9 | ...opts
|
10 | };
|
11 | const httpErrorHandlerMiddlewareOnError = async (request)=>{
|
12 | if (request.response !== undefined) return;
|
13 | if (typeof options.logger === 'function') {
|
14 | options.logger(request.error);
|
15 | }
|
16 | if (request.error.statusCode && request.error.expose === undefined) {
|
17 | request.error.expose = request.error.statusCode < 500;
|
18 | }
|
19 | if (options.fallbackMessage && (!request.error.statusCode || !request.error.expose)) {
|
20 | request.error = {
|
21 | statusCode: 500,
|
22 | message: options.fallbackMessage,
|
23 | expose: true
|
24 | };
|
25 | }
|
26 | if (request.error.expose) {
|
27 | normalizeHttpResponse(request);
|
28 | const { statusCode , message , headers } = request.error;
|
29 | request.response = {
|
30 | ...request.response,
|
31 | statusCode,
|
32 | body: message,
|
33 | headers: {
|
34 | ...headers,
|
35 | ...request.response.headers,
|
36 | 'Content-Type': typeof jsonSafeParse(message) === 'string' ? 'text/plain' : 'application/json'
|
37 | }
|
38 | };
|
39 | }
|
40 | };
|
41 | return {
|
42 | onError: httpErrorHandlerMiddlewareOnError
|
43 | };
|
44 | };
|
45 | export default httpErrorHandlerMiddleware;
|
46 |
|
47 |
|
48 |
|
\ | No newline at end of file |