我试图在 NSURLSessionDateTask 的委托方法之一中引发自定义异常。
-(void)loginWithEmail:(NSString*)email Password:(NSString*)password
{
@try {
NSURL *Url = [NSURL URLWithString:@"Http://..."];
NSData *PostData = [Post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
// preparing the request object
NSMutableURLRequest *Request = [[NSMutableURLRequest alloc] init];
[Request setURL:Url];
[Request setHTTPMethod:@"POST"];
[Request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[Request setHTTPBody:PostData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.TLSMinimumSupportedProtocol = kTLSProtocol11;
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:Request];
[dataTask resume];
}
@catch (NSException *exception) {
NSLog(@"%@", [exception description]);
@throw exception;
}
}
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
NSData *response1 = data;
// NSError *requestError = NULL; // captures the returned error (if exists)
// NSURLResponse *urlResponse = NULL; // captures the response returned by the service
NSMutableDictionary *parsedData = NULL; // holds the data after it is parsed
NSError *err = NULL;
if(!response1)
{
// If response is nil, connection timeout.
loginSuccessful = NO;
@throw [NSException exceptionWithName:@"Connection Timeout" reason:@"No Connectivity" userInfo:NULL];
}
else
{
NSString *formattedData = [[NSString alloc] initWithData:response1 encoding:NSUTF8StringEncoding];
if([formattedData rangeOfString:@"<!DOCTYPE"].location != NSNotFound || [formattedData rangeOfString:@"<html"].location != NSNotFound)
{
loginSuccessful = NO;
@throw [NSException exceptionWithName:@"Server Issue" reason:@"Could not connect to server" userInfo:NULL];
}
else
{
parsedData = [NSJSONSerialization JSONObjectWithData:response1 options:NSJSONReadingAllowFragments error:&err];
NSMutableDictionary *dict = [parsedData objectForKey:@"User"];
loginSuccessful = YES;
}
}
//handle data here
}
但是,当引发自定义异常时,“loginWithEmail”方法中的 catch 块不会捕获异常,并且我的应用程序会崩溃。在委托方法中生成异常时,异常在哪里传播?我应该如何处理?