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.
Every type that conforms to the
Error
protocol is implicitly bridged toNSError
. 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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With