使用枚举设计 Swift 中的错误类型
Using enums to design error types in Swift
也许我只是完全想多了,但我正在尝试使用枚举来处理来自 API 我正在集成的错误。
从这个 API 的 swagger 文档中,我可以看到所有可以 returned 的可能响应。我把这些写成 BaseError
枚举:
enum BaseError: Error {
case badRequest // 400
case unauthorized // 401
case forbidden // 403
case unhandledError // XXX
...
}
现在我的客户端就是我的问题开始的地方。
我最初的希望是采用这个 BaseError
枚举并根据我所在的客户扩展/添加其他案例。
类似于:
enum ClientSpecificError: BaseError {
case clientError
}
这将允许我 return 像 ClientSpecificError.unauthorized
这样的错误
现在我知道这是不可能的,因为枚举不能继承其他枚举,但我对如何实现这一目标缺少一些理解。
问题
还有其他方法可以使用枚举来实现吗?
这甚至是“最佳实践”吗?
您可以改为使用 associated values 并将低级错误存储在专用案例中。例如:
enum ClientSpecificError: Error {
case clientError
case baseError(BaseError)
}
Apple 文档:
However, it is sometimes useful to be able to store associated values of other types alongside these case values. This enables you to store additional custom information along with the case value, and permits this information to vary each time you use that case in your code.
也许我只是完全想多了,但我正在尝试使用枚举来处理来自 API 我正在集成的错误。
从这个 API 的 swagger 文档中,我可以看到所有可以 returned 的可能响应。我把这些写成 BaseError
枚举:
enum BaseError: Error {
case badRequest // 400
case unauthorized // 401
case forbidden // 403
case unhandledError // XXX
...
}
现在我的客户端就是我的问题开始的地方。
我最初的希望是采用这个 BaseError
枚举并根据我所在的客户扩展/添加其他案例。
类似于:
enum ClientSpecificError: BaseError {
case clientError
}
这将允许我 return 像 ClientSpecificError.unauthorized
现在我知道这是不可能的,因为枚举不能继承其他枚举,但我对如何实现这一目标缺少一些理解。
问题
还有其他方法可以使用枚举来实现吗?
这甚至是“最佳实践”吗?
您可以改为使用 associated values 并将低级错误存储在专用案例中。例如:
enum ClientSpecificError: Error {
case clientError
case baseError(BaseError)
}
Apple 文档:
However, it is sometimes useful to be able to store associated values of other types alongside these case values. This enables you to store additional custom information along with the case value, and permits this information to vary each time you use that case in your code.