如何使用AWS Amplify处理Lambda返回的API 400错误?
Handling 400 Validation Errors from AWS Lambda via AWS Amplify API.post
Got it, I know exactly what you're dealing with here. When your Lambda returns a 400 validation error with that structured errors array, the default catch setup you have won't easily give you access to the useful error details—Amplify wraps the error response in a specific object, so just logging err directly won't show you the field-specific messages you need.
Here's how to adjust your code to properly capture and handle those validation errors:
API.post("snippets", "snippets/", { body: data }) .then((response) => { // Handle successful response as usual console.log("Request succeeded:", response); }) .catch((err) => { // First, check if this is the 400 validation error we expect if (err.response?.status === 400) { // Extract the validation errors from Lambda's response payload const validationErrors = err.response.data.errors; // Now you can use these errors however you need—like showing field-specific messages in your UI validationErrors.forEach((error) => { console.log(`Field "${error.field}" error: ${error.message}`); // Example: If you're using a form library like Formik, you could set field errors here // setFieldError(error.field, error.message); }); } else { // Handle other unexpected errors (network issues, 500s, etc.) console.error("Unexpected error occurred:", err); } });
Key Notes:
- Amplify's API module packages non-2xx responses into an error object where the actual Lambda response lives under
err.response. Theresponse.dataproperty will be the exact JSON payload your Lambda returned. - Make sure your Lambda is formatting the error response correctly for API Gateway to pick up the 400 status code. For a Node.js Lambda, that looks like this:
exports.handler = async (event) => { const requestBody = JSON.parse(event.body); // Example validation check if (!requestBody.title) { return { statusCode: 400, headers: { "Content-Type": "application/json" }, body: JSON.stringify({ errors: [{ field: "title", message: "This field is required" }] }) }; } // Your normal success response logic here return { statusCode: 200, body: JSON.stringify({ success: true, data: requestBody }) }; }; - Double-check your API Gateway integration response settings to ensure it's passing through the Lambda response body and status code correctly—you shouldn't need any special mapping if you're returning the
statusCodefield in your Lambda response.
内容的提问来源于stack exchange,提问作者Sébastien Le Gall
相关产品推荐
相关产品推荐

