AWS Sagemaker使用boto3 Python产生错误响应的逻辑基于HTTP状态码。当请求成功时,HTTP状态码为200。当请求失败时,HTTP状态码为4xx或5xx,其中4xx表示客户端错误,5xx表示服务器端错误。boto3 Python提供了捕获API调用错误的异常机制,该机制可捕获Botocore Client Error异常,如下所示:
import boto3
from botocore.exceptions import ClientError
sagemaker_client = boto3.client('sagemaker')
try:
# 调用无效的API
response = sagemaker_client.invalid_api()
print(response)
except ClientError as e:
print("Error: {}".format(e))
在API调用失败时,将抛出Botocore Client Error异常。可以在异常信息中找到更详细的错误信息。如果需要更详细的错误信息,可以通过设置调试日志记录来捕获所有调用的信息和响应。
import boto3
import logging
from botocore.exceptions import ClientError
# 设置调试日志记录
logging.basicConfig(level=logging.DEBUG)
sagemaker_client = boto3.client('sagemaker')
try:
# 调用无效的API
response = sagemaker_client.invalid_api()
print(response)
except ClientError as e:
# 捕获Botocore Client Error异常
logging.error("Error: {}".format(e), exc_info=True)
调用以上代码示例后,将打印出Botocore Client错误的堆栈跟踪,并显示给定API的HTTP错误响应。