I want to convert the message of an exception into an NSError object so that I can use it within a try-catch block (I'm actually working on a native iOS module for React Native).
RCT_EXPORT_METHOD(myMethod:(NSDictionary *)dict
resolver:(RCTPromiseResolveBlock)resolve
rejecter:(RCTPromiseRejectBlock)reject)
{
@try {
// Do something which could throw something (NS Error or NS Exception)
resolve(nil);
} @catch (NSException *exception) {
// HERE I WANT TO TRANSFORM THE EXCEPTION exception INTO AN ERROR error
NSError error = ???
reject(@"my_error", @"Could not do something important", error);
}
}
I want to convert the exception into an NSError
because the third parameter of the reject
function (which rejects a Promise on the JS side) expects the input to be of type NSError
. I'm not sure whether my solution (using try-catch) is the best thing in this scenario..
In this Apple Developer Guide it says
You can convert an exception into an NSError object and then present the information in the error object to the user in an alert panel.
However the guide does not show a code sample for that and only shows a code sample for a second approach You can also return them indirectly in methods that include an error parameter which seems to complicated for what I want.
So, how would I convert an exception into an NSError? The API reference of NSError does not seem to contain a suitable function..
You can't convert NSException
to NSError
because NSException
they do not have the same properties. Is there any reason for catching NSException
instead of building a **NSError
mechanism? Exceptions are usually fatal and non-recoverable while Errors are non-fatal and recoverable.
If you need to go through with converting an NSException
to an NSError
anyway, you can do it manually like so:
@try {
// Something
} @catch (NSException *exception) {
NSMutableDictionary * info = [NSMutableDictionary dictionary];
[info setValue:exception.name forKey:@"ExceptionName"];
[info setValue:exception.reason forKey:@"ExceptionReason"];
[info setValue:exception.callStackReturnAddresses forKey:@"ExceptionCallStackReturnAddresses"];
[info setValue:exception.callStackSymbols forKey:@"ExceptionCallStackSymbols"];
[info setValue:exception.userInfo forKey:@"ExceptionUserInfo"];
NSError *error = [[NSError alloc] initWithDomain:yourdomain code:errorcode userInfo:info];
//use error
}