[英]Boto3 Python Lambda Customise Return Error
Is there a way to customise a Boto3 Lambda exception message in the form of a HTTP response and return it while also sending a forced failed? 有没有一种方法可以以HTTP响应的形式自定义Boto3 Lambda异常消息,并在发送强制失败的同时返回它?
Here is an example 这是一个例子
except Exception as e:
print ('\nException : failed to invoke jobs.')
print ('Error : ' + str(e) + '\n')
return {
'statusCode': 500,
'body': 'Exception : failed to invoke EMR jobs'
}
So the customised message is now returned but the Lambda still returns a job success rather than failure. 因此,现在返回了自定义消息,但是Lambda仍然返回作业成功而不是失败。
In order to send the job failure the exception block can be changed to - 为了发送作业失败,可以将异常块更改为-
except Exception as e:
print ('\nException : failed to invoke jobs.')
print ('Error : ' + str(e) + '\n')
raise
But now the custom error message has been lost. 但是现在自定义错误消息已丢失。
Is there a way to combine the custom response error message and to fail the Lambda job? 有没有一种方法可以合并自定义响应错误消息并使Lambda作业失败?
To get the custom error message as output for the lambda, you need to actually raise the exception with the custom error message. 要获取自定义错误消息作为lambda的输出,您实际上需要使用自定义错误消息引发异常。
except Exception as e:
custom_error = '\nException : failed to invoke jobs.\n'
custom_error += 'Error : ' + str(e) + '\n'
raise Exception(custom_error)
And you will get an error message like: 您将收到类似以下的错误消息:
{
"errorMessage": "Exception : failed to invoke jobs. ....",
"stackTrace": [
[
"/var/task/lambda_function.py",
3,
"my_always_fails_handler",
"raise Exception(custom_error)"
]
],
"errorType": "Exception"
}
You can find more on the AWS documentation that you can find here Python exceptions in lambdas 您可以在AWS文档中找到更多信息,您可以在此处找到lambdas中的Python异常
You didn't mention it, but you're probably using AWS API Gateway to in front of your lambda. 您没有提及它,但是您可能在lambda前面使用了AWS API Gateway。
You can use API Gateway "integration response" to transform your failed result to the HTTP response. 您可以使用API网关“集成响应”将失败的结果转换为HTTP响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.