-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproblemResponse.ts
More file actions
45 lines (44 loc) · 1.43 KB
/
problemResponse.ts
File metadata and controls
45 lines (44 loc) · 1.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import type { MiddlewareObj } from '@middy/core'
import { HttpStatusCode, ProblemDetailError } from '@nrfcloud/problem-detail'
import { formatTypeBoxErrors } from '@nrfcloud/validate-with-typebox'
import type {
APIGatewayProxyEventV2,
APIGatewayProxyStructuredResultV2,
Context as LambdaContext,
} from 'aws-lambda'
import { aProblem } from './aProblem.ts'
import { ValidationFailedError } from './validateInput.ts'
import { ResponseValidationFailedError } from './validateResponse.ts'
export const problemResponse = (): MiddlewareObj<
APIGatewayProxyEventV2,
APIGatewayProxyStructuredResultV2,
Error,
LambdaContext
> => ({
onError: async (req) => {
if (req.response !== undefined) return
if (req.error instanceof ResponseValidationFailedError) {
req.response = aProblem({
title: 'Response validation failed',
status: HttpStatusCode.INTERNAL_SERVER_ERROR,
detail: formatTypeBoxErrors(req.error.errors),
})
} else if (req.error instanceof ValidationFailedError) {
req.response = aProblem({
title: 'Validation failed',
status: HttpStatusCode.BAD_REQUEST,
detail: formatTypeBoxErrors(req.error.errors),
})
} else if (req.error instanceof ProblemDetailError) {
req.response = aProblem(req.error.problem)
} else {
req.response = aProblem({
title:
req.error instanceof Error
? req.error.message
: 'Internal Server Error',
status: HttpStatusCode.INTERNAL_SERVER_ERROR,
})
}
},
})