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.
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.
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.
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