Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 268
villapossu Avatar asked Oct 30 '22 09:10

villapossu


1 Answers

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.
    }
}
like image 106
ridvankucuk Avatar answered Nov 15 '22 06:11

ridvankucuk