-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy patherror-response.js
More file actions
61 lines (53 loc) · 1.71 KB
/
error-response.js
File metadata and controls
61 lines (53 loc) · 1.71 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
53
54
55
56
57
58
59
60
61
import CircularJSON from 'circular-json'
import AbstractLambdaPlugin from './abstract-lambda-plugin'
import PluginHook from '../enums/hooks'
import LambdaType from '../enums/lambda-type'
/**
* Error mapping callback used to format the supplied error into an error response body.
*
* @callback errorMapperCallback
* @param {Error} error thrown error
* @returns {Object} response body obj
*/
/**
* ErrorResponse plugin for Api Gateway lambdas.
*/
export default class ErrorResponse extends AbstractLambdaPlugin {
/**
* ErrorResponse constructor.
*
* @param {errorMapperCallback=} defaultErrorResponse default error response fn
*/
constructor (defaultErrorResponse = null) {
super('errorResponse', LambdaType.API_GATEWAY)
this._defaultErrorResponse = defaultErrorResponse
this.addHook(PluginHook.ON_ERROR, this.mapErrorResponse.bind(this))
}
/**
* Map error to a custom body
*
* @param {errorMapperCallback=} errorResponseFn error response fn
*/
mapErrorResponse (errorResponseFn = null) {
const fn = errorResponseFn || this._defaultErrorResponse || null
return (req, res, error, context, done) => {
let errorBody
if (fn !== null) {
errorBody = fn(error)
} else {
const errorObj = error
const errorType = error && error.constructor && error.constructor.name
errorBody = {
error: {
message: error.message || 'Unknown error. No error specified',
name: errorType !== 'Object' ? errorType : 'Unknown',
...errorObj,
_stackTrace: (error.stack || '').split('\n').map(x => x.trim())
}
}
}
res.body = CircularJSON.stringify(errorBody)
done()
}
}
}