serverless での エラーマッピングの仕方。
そもそものエラーの返し方はこちら。
return context.done(new Error("invalid type :" + type ));
レスポンスコードを変えたりしたい時は、 s-function.json の responses をいじる 。
こんな感じでコンソール上の「Lambda Error Regex」を「selectionPattern」に 設定する。
デフォルトだとstackTraceがそのまま出てしまうのでテンプレートを設定している。
"responses": { "400": { "statusCode": "400", "selectionPattern": "invalid type.*", "responseTemplates": { "application/json": "#set($inputRoot = $input.path('$'))\n{\n \"errorMessage\": \"$inputRoot.errorMessage\",\n \"errorType\": \"$inputRoot.errorType\"#if($context.stage == \"development\"),\n \"stackTrace\": $inputRoot.stackTrace#end\n\n}" } },
テンプレートを見やすく整形するとこんな感じ。
stageでstackTraceの出力を切り替えている。
#set($inputRoot = $input.path('$')) { "errorMessage": "$inputRoot.errorMessage", "errorType": "$inputRoot.errorType"#if($context.stage == "development"), "stackTrace": $inputRoot.stackTrace #end }