You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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. The response.data property 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 statusCode field in your Lambda response.

内容的提问来源于stack exchange,提问作者Sébastien Le Gall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:20:00