LegibleError 的目标是防止你向用户展示如下字符串
操作无法完成。(ThirdPartyModule.(未知上下文 at 0xx10d6b4a44).SomeError 错误 0。)
这个字符串是 Swift Error
的默认 localizedDescription
。使用 LegibleError 代替,你将得到更像这样的结果
操作无法完成。(ThirdPartyModule.SomeError.networkFailure(http: 503))
如果你有一个像这样的 Error
enum SystemError: Error {
case databaseFailure(internalCode: Int)
}
let error = SystemError.databaseFailure
// ^^ obviously you’d get this from a callback or `catch` in the real-world
let alert = UIAlertController(…)
alert.message = error.localizedDescription
present(alert)
警报将显示
操作无法完成。(MyModule.(未知上下文 at 0xx10d6b4a44).SystemError 错误 0。)
但是如果我们使用 .legibleLocalizedDescription
import LegibleError
let alert = UIAlertController(…)
alert.message = error.legibleLocalizedDescription
present(alert)
警报将显示
操作无法完成。(SystemError.databaseFailure(internalCode: 34))
仍然不是很好,但在错误报告中更有用。
如果你想要一个更好的消息,实现 LocalizedError
,这将使 localizedDescription
和 legibleLocalizedDescription
都返回你指定的字符串
enum SystemError: LocalizedError {
case databaseFailure
var errorDescription: String? {
switch self {
case databaseFailure(let code):
return "A serious database failure occurred. Contact support. (#\(code))"
}
}
}
警报将显示
发生了严重的数据库故障。请联系支持。( #34)
LegibleError 存在的原因是
LocalizedError
legibleDescription
(见下一节)。这样
let msg = "There was an error (\(error))"
会给你这样的结果
发生了一个错误 (databaseFailure)
这会丢失枚举类型上下文;使用 legibleDescription
let msg = "There was an error! \(error.legibleDescription)"
发生了一个错误 (SystemError.databaseFailure(internalCode: 34))
legibleDescription
之于 description
,正如 legibleLocalizedDescription
之于 localizedDescription
。 legibleDescription
始终适合于向*你*,开发者,传达发生了什么错误。在日志中使用它,并用于补充给用户的良好消息。
Linux 有点落后,通常在 Linux 上你只会得到 The operation could not be completed
。我们完全支持 Linux。
如果你或你的公司依赖这个项目,请考虑赞助,这样我就有理由进行维护。
SwiftPM
package.append(.package(url: "https://github.com/mxcl/LegibleError.git", from: "1.0.0"))
CocoaPods
pod 'LegibleError', '~> 1.0'
Carthage
等待中:@Carthage#1945。