Update NSError UserInfo

I am trying to update an NSError object with additional information. For example, an api call may fail, and I want to update the error object returned from the api class with information about the view controller (method name that caused the error, client message, any additional information). There is no setter method for the UserInfo dictionary, and trying to set a value for the dictionary throws an exception (it seems to me that it does not match the code with the key values). I was thinking of creating a new NSError object with updated user information, but I was not sure if I could lose the information.

Question

What is the best way to update the NSError object user information dictionary?

+6
source share
3 answers

The easiest way to do this is to get a modified copy of the userInfo dictionary and add whatever you like. Then you will need to create a new NSError (since the setUserInfo :) method is missing with the same domain and code as the source.

+3
source

The canonical approach would be to make the new NSError all its own, and then put the original NSError into the userInfo dictionary under the NSUnderlyingErrorKey key. This is a slightly different result, but as far as I can tell, NSErrors quite intentionally unchanged.

+8
source

With quick extensions 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) } } 

using:

 var yourError = NSError(domain: "com.app.your", code: 999, userInfo: nil) yourError = yourError.addItemsToUserInfo(["key1":"value1","key2":"value2"]) 
+7
source

Source: https://habr.com/ru/post/952372/


All Articles