I have a lambda function where I am making an api call which returns uuid on success and errorMessage on failure
try:
#make api call
return {
'statusCode': 200,
'body': json.dumps({'uuid':uniqueuuid})
}
except Exception as error:
return {
'statusCode': 500,
'body': json.dumps({'errorMessage':f"P56"})
}
For the success response from lambda, I can able to extract the body values in C#. In the below method, I can able to get the uuid value returned from lambda. But when there is an exception from lambda, I want to extract the errorMessage value which is "P56". On exception from lambda, it is picked up by catch block and the exception has 'remote server returned an error 500' which is correct, but how do I extract the status code and errorMessage value in the exception block. Or should I return statusCode as 200 for both success and failure from lambda and extract either uuid or errorMessage in the try block of C#.
C# method:
private JObject GetDataFromLambda()
{
JObject jObj = null;
try
{
using (var client = new WebClient())
{
//define payload data
var result = client.UploadString($"https://xxx",
WebRequestMethods.Http.Post, data)
jObj = JObject.Parse(result);
var uuid= jObj["uuid"].Value<string>();
}
}
catch (Exception ex)
{
}
}
CodePudding user response:
Can you try writing the below code in Lambda?
raise Exception('Something is wrong')
CodePudding user response:
Based on the documentation, something like this should work:
private JObject GetDataFromLambda(string data)
{
JObject jObj = null;
try
{
using (var client = new WebClient())
{
//define payload data
var result = client.UploadString($"https://xxx",
WebRequestMethods.Http.Post, data)
jObj = JObject.Parse(result);
var uuid = jObj["uuid"].Value<string>();
}
}
catch (WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
{
var response = (HttpWebResponse)ex.Response;
var encoding = System.Text.Encoding.UTF8;
var sr = new StreamReader(response.GetResponseStream(), encoding);
string json = sr.ReadToEnd();
var errObj = JObject.Parse(json);
var httpStatusCode = response.StatusCode;
var errorMessage = errObj["errorMessage"].Value<string>();
}
}
return jObj;
}
Documentation:
WebException.Response: https://docs.microsoft.com/en-us/dotnet/api/system.net.webexception.response?view=net-6.0#system-net-webexception-response
HttpWebResponse.GetResponseStream(): https://docs.microsoft.com/en-us/dotnet/api/system.net.httpwebresponse.getresponsestream?view=net-6.0#system-net-httpwebresponse-getresponsestream
