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

AWS Lambda自定义错误在Axios中显示为通用错误的问题排查

问题

我用Serverless创建了一个由HTTP API事件触发的Python AWS Lambda函数。函数尝试返回API Gateway传入的context对象,但因context无法序列化触发异常。异常块返回了自定义错误内容,在AWS控制台能正常查看,但通过Axios调用时,仅收到状态码500的通用"Internal Server Error"错误,无法获取自定义错误信息。尝试多种序列化方式及客户端属性排查均无效,期望Axios能获取到自定义错误体。

原代码

Python Lambda函数代码

def get_context(event, context):
try:
    typ = str(type(context))
    body = {
        "context_type": typ,
        "context": context
    }
    return {"statusCode": 200, "body": json.dumps(body)}
except Exception as e:
    estr = f"other python error: {e}"
    logger.error(estr) # AWS CloudWatch
    body = {"message": "FAIL", "error": estr}
    return {"statusCode": 500, "body": body}

客户端调用代码

async apiPost(apiPath) {
  // apiPath = "/public/test/context"
  const apiName = "{resource defined in Amplify Configuration}";
  const myInit = {
    headers: {}, // OPTIONAL
    response: true, // OPTIONAL (return the entire Axios response object instead of only response.data)
  };
  try {
    const res = await API.post(apiName, apiPath, myInit); // aws-amplify API (Axios)
    this.api_res = JSON.stringify(res, null, 2);
    this.api_res_type = "Response";
  } catch (e) {
    this.api_res = axiosErrorHandler(e); // Just my attempts to dig through the error object...
    this.api_res_type = "ERROR";
  }
},

错误处理函数

function axiosErrorHandler(err) {
  let res = {};
  if (err.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    res["condition"] = "Server Responded";
    res["body"] = err.response.data;
    res["statusCode"] = err.response.status;
    res["headers"] = err.response.headers;
  } else if (err.request) {
    // The request was made but no response was received
    // `err.request` is an instance of XMLHttpRequest in the browser and an instance of
    // http.ClientRequest in node.js
    res["condition"] = "No Server Response";
    res["request"] = err.request;
  } else {
    // Something happened in setting up the request that triggered an Error
    res["condition"] = "Request Setup Error";
    res["message"] = err.message;
  }
  return JSON.stringify(res, null, 2);
}
解决方案

核心问题有两个:

  1. Lambda异常返回的body未做JSON序列化,直接返回Python字典,API Gateway无法正确解析,导致返回默认500错误。
  2. 未指定Content-Type响应头,客户端无法识别返回内容格式。

修改后的Lambda函数代码:

import json
import logging

logger = logging.getLogger()
logger.setLevel(logging.ERROR)

def get_context(event, context):
    try:
        typ = str(type(context))
        body = {
            "context_type": typ,
            "context": context
        }
        return {
            "statusCode": 200,
            "headers": {"Content-Type": "application/json"},
            "body": json.dumps(body)
        }
    except Exception as e:
        estr = f"other python error: {e}"
        logger.error(estr)
        body = {"message": "FAIL", "error": estr}
        return {
            "statusCode": 500,
            "headers": {"Content-Type": "application/json"},
            "body": json.dumps(body)
        }

修改说明

  • 确保导入json模块,用于序列化响应体。
  • 成功和异常响应都添加headers字段,指定Content-Type: application/json,明确告诉客户端返回内容格式。
  • 异常块的body通过json.dumps()序列化为JSON字符串,API Gateway才能正确转发自定义错误内容给客户端。

完成以上修改后,Axios的错误处理函数就能通过err.response.data获取到自定义的错误体内容。

内容的提问来源于stack exchange,提问作者Brian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:34:55