简体   繁体   中英

How can I get a Lambda using AWS Gateway to return HTTP error status code in C#

I'm trying to return status error codes (ex. 500, 400, 401) through my AWS Gateway and can't seem to figure it out.

I've seen a few examples, where they do something like:

return context.fail('Bad Request: You submitted invalid input');

However, there is no fail or succeed methods on the ILambdaContext object.

Here's what I've got so far (non-working)

Lambda Code:

 var addressresponse = new AddressValidationResponse();
            addressresponse.Errors = new string[1];
            addressresponse.Errors[0] = "test error";
            addressresponse.Reason = "client_error";

 return addressresponse;

自定义错误模型

整合响应

方法响应

I think I'm close, but I'm still getting a 200 back with the response of:

{
  "Reason": "client_error",
  "Errors": [
    "test error"
  ]
}

What am I missing here?

您需要在 C# lambda 函数中引发异常,并使用 API 网关控制台将特定错误代码映射到响应映射模板中的 HTTP 响应代码。

You can use the APIGatewayHttpApiV2ProxyResponse to wrap your response, like below:

public static async Task<APIGatewayHttpApiV2ProxyResponse?> FunctionHandler(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context)
{
    var response = new APIGatewayHttpApiV2ProxyResponse();
    try
    {
        response.Body = await DoSomeWorkAsync();
        response.StatusCode = (int)HttpStatusCode.OK;
    }
    catch (Exception ex)
    {
        response.StatusCode = (int)HttpStatusCode.InternalServerError;
        response.Body = JsonSerializer.Serialize(new { error = ex.Message }) ;
    }

    return response;
}

I answered something similar here

Basically you need to return a response object that APIG recognises.

There's C# example here

I would say I don't C# in the context Lambda though, basically you need to return headers, statusCode and response Body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM