我在我的应用中使用AWS iOS SDK,最近我测试了无网络情况。这是我的代码:
dispatch_queue_t Q = dispatch_queue_create("ec2_instance_fetch", NULL);
dispatch_async(Q, ^{
AmazonEC2Client *client = [[AmazonEC2Client alloc] initWithAccessKey:[ESCredentialsManager accessKey] withSecretKey:[ESCredentialsManager secretKey]];
client.endpoint = [NSString stringWithFormat:@"https://%@", [ESRegionManager endpointForRegion:[ESRegionManager activeRegionObject]]];
EC2DescribeInstancesResponse *response = [client describeInstances:[[EC2DescribeInstancesRequest alloc] init]];
NSMutableArray *temp = @[].mutableCopy;
for (EC2Reservation *reserv in response.reservations) {
for (EC2Instance *instance in reserv.instances) {
[temp addObject:instance];
}
}
self.instances = temp;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
在无连接情况下,它会抛出此错误:
*** Terminating app due to uncaught exception 'AmazonClientException', reason: 'Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo=0x16e55460 {NSErrorFailingURLStringKey=https://ec2.us-east-1.amazonaws.com/, NSErrorFailingURLKey=https://ec2.us-east-1.amazonaws.com/, NSLocalizedDescription=The Internet connection appears to be offline., NSUnderlyingError=0x16dea2c0 "The Internet connection appears to be offline."}'
*** First throw call stack:
(0x301adf4b 0x3a91c6af 0xbbae1 0xbb31d 0xba6c7 0xba177 0xbd3ab 0xa2bab 0x3adffd1b 0x3ae06273 0x3ae0606b 0x3ae06ce1 0x3ae06f59 0x3af41dbf 0x3af41c84)
libc++abi.dylib: terminating with uncaught exception of type AmazonServiceException
(lldb)
所以我试着简单地捕捉到这样的错误:
dispatch_queue_t Q = dispatch_queue_create("ec2_instance_fetch", NULL);
dispatch_async(Q, ^{
@try {
AmazonEC2Client *client = [[AmazonEC2Client alloc] initWithAccessKey:[ESCredentialsManager accessKey] withSecretKey:[ESCredentialsManager secretKey]];
client.endpoint = [NSString stringWithFormat:@"https://%@", [ESRegionManager endpointForRegion:[ESRegionManager activeRegionObject]]];
EC2DescribeInstancesResponse *response = [client describeInstances:[[EC2DescribeInstancesRequest alloc] init]];
NSMutableArray *temp = @[].mutableCopy;
for (EC2Reservation *reserv in response.reservations) {
for (EC2Instance *instance in reserv.instances) {
[temp addObject:instance];
}
}
self.instances = temp;
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
@catch (NSError *error) {
NSLog(@"Error: %@", error);
}
});
但它仍然失败,同样的错误,应用程序崩溃。为什么我不能这样捕捉到这个错误?我怎么能?
答案 0 :(得分:3)
不要抓住NSError
。抓住NSException
。