Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to extend NSError

Sorry for asking this question. I know in java we are extending Exception class for custom exceptions. But I don't see any scenarios for that in objective c.

So my question, Is it a good practice to extend NSError and introducing custom errors? If so when we should extend NSError class. I checked documentation for this too. But I can't see overriding notes for NSError.

like image 907
uiroshan Avatar asked Oct 27 '14 13:10

uiroshan


2 Answers

While I agree that you shouldn't subclass NSError, it is very useful to put categories on it, and I do this regularly. For example, say your system often posts errors that come from some JSON block. I'd find it very convenient to create a category like:

@interface NSError (MyErrors)
// Construct an NSError from data in JSON.
// Include full JSON response in the userInfo
+ (NSError *)myErrorWithJSON:(JSON *)json;

// Parse the text out of the user info
- (NSString *)myErrorMessage;

// The full JSON error block as a string
- (NSString *)myErrorJSON;

// BOOLs can be helpful sometimes, or you could return an enum for use in a switch.
- (BOOL)myIsNetworkError;
- (BOOL)myIsAuthError;
@end

I often write little helpers to construct NSError more simply, construct the userinfo the way I want, and the pull data back out of the userinfo without callers needing to know its internal representation. I find this to be a very good form of data-hiding, and encourages the use of more descriptive messages.

Similarly, even for smaller projects, I often create a +myErrorWithCode:localizedDescription: category method. I know my domain, so I usually don't need to pass that, and this makes it a lot easier to set the NSLocalizedDescription key in the user info. Again, this encourages better errors by making them easier to create, and makes it easier to change the implementation details of your error handling.

like image 70
Rob Napier Avatar answered Sep 22 '22 06:09

Rob Napier


I've never seen it done and that's because NSError is already very versatile. It allows the type of error to be defined by setting the domain and code properties and allows arbitrary additional information to be attached within the userInfo dictionary.

So, no, it's not good practice.

like image 27
trojanfoe Avatar answered Sep 19 '22 06:09

trojanfoe