Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update NSError UserInfo

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.

Question

What's the best way to update the user info dictionary of an NSError object?

like image 869
JeffRegan Avatar asked Aug 23 '13 15:08

JeffRegan


3 Answers

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.

like image 198
Steve Wilford Avatar answered Nov 01 '22 12:11

Steve Wilford


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"])
like image 29
Daniel Creagh Avatar answered Nov 01 '22 12:11

Daniel Creagh


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.

like image 27
ipmcc Avatar answered Nov 01 '22 11:11

ipmcc