-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patherror-status-code-map.js
More file actions
52 lines (46 loc) · 1.49 KB
/
error-status-code-map.js
File metadata and controls
52 lines (46 loc) · 1.49 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
46
47
48
49
50
51
52
import AbstractLambdaPlugin from './abstract-lambda-plugin'
import PluginHook from '../enums/hooks'
import LambdaType from '../enums/lambda-type'
/**
* Error status code map definition.
*
* @typedef {Object} ErrorStatusCode
* @type {object}
* @property {Error} error Error type
* @property {number} status status code
*/
/**
* Error status code map.
*
* Map an error thrown to an appropariate HTTP status code for ApiGateway
*/
export default class ErrorStatusCodeMap extends AbstractLambdaPlugin {
/**
* Error status code map constructor.
*
* @param {ErrorStatusCode[]=} statusMap list of errors and their http status codes
*/
constructor (statusMap = []) {
super('errorMap', LambdaType.API_GATEWAY)
this._defaultStatusMap = statusMap
this.addHook(PluginHook.ON_ERROR, this.errorMapper.bind(this))
}
/**
* Map errors to custom status codes.
*
* Using the error, check against a known list of errors and their appropriate status codes to
* set the api-gateway response status code to. If no mapping found, default to a 500 response
* code.
*
* @param {ErrorStatusCode[]=} errorMap list of errors and their http status codes
*/
errorMapper (errorMap) {
errorMap = errorMap || []
const completeErrorMap = errorMap.concat(this._defaultStatusMap)
return (req, res, error, context, done) => {
const err = completeErrorMap.find(e => error instanceof e.error)
res.statusCode = (err && err.status) || 500
done()
}
}
}