Created
August 18, 2015 22:24
-
-
Save Ziewvater/9df5b612bd842e22fb83 to your computer and use it in GitHub Desktop.
Grabbing correct PFErrorCode for an error returned in a Parse cloud code response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Class that can retrieve nested error messages from Parse cloud code responses | |
// | |
// If you've got cloud code that does something like | |
// | |
// thing.save().then(function(savedThing) { | |
// response.success(); | |
// }, function(error) { | |
// response.error(error); | |
// }); | |
// | |
// Then you might have had issues trying to get the real error code from a returned error response. | |
// That's because when you call `response.error(error)`, you're not responding with the error object | |
// itself, you're translating it into a string and adding it as an optional message on the error response. | |
// | |
// This means that all of the errors returned by your cloud code will all have code 141 when you inspect them, | |
// and the true error code/message are hidden in the error's `userInfo` dictionary as a String. | |
// To get the real error code, you'll need to dig in to find the stringified error, convert it to JSON, and | |
// construct your own error code off of that. | |
class PFErrorHelper { | |
class func nestedErrorCode(error: NSError) -> PFErrorCode { | |
if let innerDict = error.userInfo, errorMessageString = innerDict["error"] as? NSString, jsonData = errorMessageString.dataUsingEncoding(NSUTF8StringEncoding) { | |
var parsingError: NSError? | |
if let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.AllowFragments, error: &parsingError) as? [NSString : AnyObject], code = json["code"] as? Int, errorCode = PFErrorCode(rawValue: code) { | |
return errorCode | |
} else if parsingError != nil { | |
NSLog("Error determining nested error: \(parsingError)") | |
return PFErrorCode.ErrorInternalServer | |
} | |
} | |
return PFErrorCode.ErrorInternalServer | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment