我想将异常消息转换为 NSError 对象,以便我可以在 try-catch 块中使用它(我实际上正在处理 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);
}
}
我想将异常转换为
NSError
因为reject
的第三个参数函数(在 JS 端拒绝 Promise)期望输入类型为 NSError
.我不确定我的解决方案(使用 try-catch)是否在这种情况下是最好的。在 this Apple Developer Guide它说
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.
但是,该指南没有显示代码示例,只显示了第二种方法的代码示例您还可以在包含错误参数的方法中间接返回它们,这似乎对我想要的东西来说很复杂。
那么,如何将异常转换为 NSError 呢? The API reference of NSError似乎没有包含合适的功能..
最佳答案
您无法转换 NSException
至 NSError
因为 NSException
它们没有相同的属性。有什么理由抓NSException
而不是建立一个 **NSError
机制?异常通常是致命的且不可恢复的,而错误是非致命的且可恢复的。
如果您需要转换 NSException
到 NSError
无论如何,您可以像这样手动完成:
@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
}
关于ios - 如何将异常转换为 NSError 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43561531/