定制错误响应

有效的错误处理对于构建用户友好的 AI 应用非常重要。BentoML 通过允许您为 服务 (Service) 定制错误处理逻辑来促进这一点。

本文档介绍如何在 BentoML 服务 (Service) 中定义自定义异常类和错误处理逻辑。

自定义异常类

要定义自定义异常,请继承 BentoMLException 或其子类之一,例如以下示例中的 InvalidArgument

注意

BentoML 保留了错误代码 401、403 和所有大于 500 的错误代码。在自定义异常中应避免使用这些代码。

import bentoml
from bentoml.exceptions import InvalidArgument, BentoMLException
from http import HTTPStatus

# Define a custom exception for method not allowed errors
class MyCustomException(BentoMLException):
    error_code = HTTPStatus.METHOD_NOT_ALLOWED

# Define a simple custom exception for invalid argument errors
class MyCustomInvalidArgsException(InvalidArgument):
    pass


@bentoml.service
class MyService:

    @bentoml.api
    def test1(self, text: str) -> str:
        # Raise the custom method not allowed exception
        raise MyCustomException("This is a custom error message.")

    @bentoml.api
    def test2(self, text: str) -> str:
        # Raise the custom invalid argument exception
        raise MyCustomInvalidArgsException("This is a custom error message.")

更多信息,请参阅异常 API