Skip to content

Instantly share code, notes, and snippets.

@mishagray
Last active January 14, 2016 05:33
Show Gist options
  • Save mishagray/75dd38ffc62f10cef8d7 to your computer and use it in GitHub Desktop.
Save mishagray/75dd38ffc62f10cef8d7 to your computer and use it in GitHub Desktop.
NSErrorType protocol
// ----------------------------------------------------------------------
// MARK: NSErrorType protocol, with JSON extensions for NSError
// ----------------------------------------------------------------------
/** so if you have a ErrorType var, and you want to test for NSError ex (e is NSError), it always succeeds.
it can sometimes be hard to test for NSError.
but you can test for protocol conformance.
so now:
e as? NSErrorType
will only succeed is e is actually NSError.
this shortcircuits the built in Swift 2 ErrorType to NSError conversion
*/
public protocol NSErrorType {
var userInfo: [NSObject : AnyObject] { get }
var domain: String { get }
var code: Int { get }
}
extension NSError : NSErrorType {
convenience init(error : ErrorType, jsonData : JSON) {
let e = error as NSError
var newUserInfo = e.userInfo
newUserInfo[SquarespaceServerErrorDataKey] = jsonData.object
self.init(domain: e.domain, code: e.code, userInfo:newUserInfo)
}
}
public extension NSErrorType {
var jsonData : JSON? {
get {
if let rawObject = self.userInfo[SquarespaceServerErrorDataKey] {
return JSON(rawObject)
}
else {
return nil
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment