Swift 3.1: Crash when custom error is converted to NSError to access its domain property

放肆的年华 提交于 2019-12-10 13:45:56

问题


My Swift app has a custom error system where MyError is just a simple class conforming to Error. Now the app seems to crash whenever a third-party library (PromiseKit) tries to convert this error to NSError and then to access its domain property. In my own code, doing this works as expected, so why does it crash in the library and what's the proper way of dealing with it?

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)

回答1:


While casting from Error to NSError it is trying to access the errorCode and errorDomain. Adding these extensions fixed my problem in the same case.

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.
    }
}


来源:https://stackoverflow.com/questions/43225036/swift-3-1-crash-when-custom-error-is-converted-to-nserror-to-access-its-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!