我的Swift应用程序有一个自定义错误系统,其中MyError
只是一个符合Error
的简单类。现在,只要第三方库(PromiseKit)尝试将此错误转换为NSError
,然后访问其domain
属性,应用程序就会崩溃。在我自己的代码中,这样做会按预期工作,那么为什么它会在库中崩溃以及处理它的正确方法是什么?
Crashed: com.apple.main-thread
0 libswiftCore.dylib 0x1011d86d8 _hidden#19226_ (__hidden#19178_:1788)
1 libswiftCore.dylib 0x1011cda3c _hidden#19206_ (__hidden#19447_:4045)
2 libswiftCore.dylib 0x1011cda3c _hidden#19206_ (__hidden#19447_:4045)
3 libswiftCore.dylib 0x1011cdc90 swift_getTypeName (__hidden#19406_:1731)
4 AppName 0x1001dafec specialized (_adHocPrint_unlocked<A, B where ...> (A, Mirror, inout B, isDebugPrint : Bool) -> ()).(printTypeName #1)<A, B where ...> (Any.Type) -> () (MyError.swift)
5 AppName 0x1001db4f0 specialized specialized _adHocPrint_unlocked<A, B where ...> (A, Mirror, inout B, isDebugPrint : Bool) -> () (MyError.swift)
6 AppName 0x1001dafb4 specialized _debugPrint_unlocked<A, B where ...> (A, inout B) -> () (MyError.swift)
7 AppName 0x1001dac00 protocol witness for Error._domain.getter in conformance MyError (MyError.swift)
8 libswiftCore.dylib 0x10104fa14 swift_stdlib_getErrorDomainNSString (__hidden#18979_:140)
9 libswiftCore.dylib 0x1011f96d8 _hidden#21248_ (__hidden#21275_:440)
10 PromiseKit 0x100dc7d4c Error.isCancelledError.getter (Error.swift:145)
答案 0 :(得分:2)
从Error转换为NSError时,它尝试访问errorCode
和errorDomain
。添加这些扩展程序可以解决我的问题。
extension CustomError: LocalizedError {
public var errorDescription: String? {
return "Some localized description"
}
}
extension CustomError: CustomNSError {
public static var errorDomain: String {
return "Some Domain Name"
}
public var errorCode: Int {
return 204 //Should be your custom error code.
}
}