I'm trying to update an NSError
object with more information. For example, an api call may fail and I want to update the error object returned from the api class with view controller information (method name that caused error, client message, any additional info). There isn't a setter method for the UserInfo
dictionary and trying to set a value for the dictionary raises an exception (Not key value code compliant I believe). I thought about creating a new NSError
object with the updated user info, but I wasn't sure if I might lose information.
What's the best way to update the user info dictionary of an NSError object?
Easiest way to do this would be to get a mutable copy of the userInfo
dictionary and add whatever you like to that. Then you would have to create a new NSError
(since there is not setUserInfo: method) with the same domain and code as the original one.
With swift extentions it's easy:
extension NSError {
func addItemsToUserInfo(newUserInfo: Dictionary<String, String>) -> NSError {
var currentUserInfo = userInfo
newUserInfo.forEach { (key, value) in
currentUserInfo[key] = value
}
return NSError(domain: domain, code: code, userInfo: currentUserInfo)
}
}
usage:
var yourError = NSError(domain: "com.app.your", code: 999, userInfo: nil)
yourError = yourError.addItemsToUserInfo(["key1":"value1","key2":"value2"])
The canonical approach would be to make a new NSError
all your own and then put the original NSError
in the userInfo
dictionary under the key NSUnderlyingErrorKey
. This is a slightly different result, but as best I can tell NSErrors
are quite intentionally immutable.
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