Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the CustomNSError protocol do and why should I adopt it?

Tags:

swift

What does the CustomNSError protocol do and why should I adopt it?
The documentation provided by Apple only states:

Describes an error type that specifically provides a domain, code, and user-info dictionary.

I already searched on google, but couldn't find anything related to my questions there.

like image 519
Nick Podratz Avatar asked Dec 16 '16 17:12

Nick Podratz


1 Answers

Every type that conforms to the Error protocol is implicitly bridged to NSError. This has been the case since Swift 2, where the compiler provides a domain (i.e., the mangled name of the type) and code (based on the discriminator of the enumeration type).

So you need CustomNSError, LocalizedError and RecoverableError for explicit runtime mapping to NSError.

More info here.

Example:

// Errors

enum ServiceError: Int, Error, CustomNSError {
    case unknownError = -1000
    case serverReturnBadData

    //MARK: - CustomNSError

    static var errorDomain: String = "reverse.domain.service.error"

    var errorCode: Int { return self.rawValue }
    var errorUserInfo: [String : Any] { return [:]  } //TODO: Return something meaningful here
}

extension NSError {

    var serviceError: ServiceError? {
        return (self.domain == ServiceError.errorDomain
            ? ServiceError(rawValue: self.code)
            : nil)
    }

    convenience init(serviceError: ServiceError) {
        self.init(
            domain: ServiceError.errorDomain,
            code: serviceError.rawValue,
            userInfo: serviceError.errorUserInfo)
    }
}
like image 79
apetrov Avatar answered Oct 19 '22 13:10

apetrov