how to correctly use integration response mapping in aws api gateway to return different http codes

谁说我不能喝 提交于 2019-12-12 22:12:42

问题


I can't seem to set my integration response for errors using the amazon api gateway

I added an integration response but it does not return the 400 error, instead it continues to return 200 response with

{
  "errorMessage": "foose",
  "errorType": "Error",
  "stackTrace": [
    "exports.handler (/var/task/index.js:11:19)"
  ]
}

回答1:


If you are using the Java, you need to throw an Exception. I made the mistake of trying to return the error information. The Lambda Error Regex parses the Exception message so if you throw this:

throw new Exception("Failed: Something bad happened!");

and replace your foo.* with Failed: .* it will use the 400 status code.


If you are using NodeJS, you can use context.fail('Failed: Something bad happened!'); to get the same result




回答2:


.*"Failed:".*

This is the correct syntax for Lambda Regex. Also, in nodeJS (as per your example above) it's easier to construct your own error object and add status for easier mapping, e.g.:

var myError = {}
myError.status = "userError"; //use this for 400 and "serverError" for 500
myError.message = err.stackTrace; //message body

Finally you need to return

context.fail(JSON.stringify(myError));

If you don't have response mapping set up properly.



来源:https://stackoverflow.com/questions/31346577/how-to-correctly-use-integration-response-mapping-in-aws-api-gateway-to-return-d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!