Errors with NSError
Objective-C distinguishes two kinds of failure:
| Kind | Examples | Mechanism |
|---|---|---|
| expected, recoverable errors | file not found, invalid input, network down | return NO/nil and fill in an NSError |
| programmer mistakes | index out of range, calling a missing method | exceptions (next lesson), usually crash |
Cocoa uses exceptions only for bugs. Everything a user or the environment can cause is reported with NSError.
The NSError ** pattern
A method that can fail returns BOOL (or an object that may be nil) and takes a last parameter error:(NSError **)error, a pointer to an NSError * variable that it fills in on failure:
#import <Foundation/Foundation.h>
static NSString * const ParserErrorDomain = @"com.example.parser";
typedef NS_ENUM(NSInteger, ParserError) {
ParserErrorEmpty = 1,
ParserErrorNotANumber = 2,
};
NSNumber *parseAge(NSString *text, NSError **error) {
if (text.length == 0) {
if (error) {
*error = [NSError errorWithDomain:ParserErrorDomain
code:ParserErrorEmpty
userInfo:@{NSLocalizedDescriptionKey: @"The age is empty."}];
}
return nil;
}
NSScanner *scanner = [NSScanner scannerWithString:text];
NSInteger value;
if (![scanner scanInteger:&value] || !scanner.isAtEnd) {
if (error) {
NSString *msg = [NSString stringWithFormat:@"'%@' is not a whole number.", text];
*error = [NSError errorWithDomain:ParserErrorDomain
code:ParserErrorNotANumber
userInfo:@{NSLocalizedDescriptionKey: msg}];
}
return nil;
}
return @(value);
}
int main(void) {
@autoreleasepool {
for (NSString *input in @[@"42", @"", @"forty", @"7x"]) {
NSError *error = nil;
NSNumber *age = parseAge(input, &error);
if (age) {
NSLog(@"'%@' -> %@", input, age);
} else {
NSLog(@"'%@' failed: %@ (code %ld)", input, error.localizedDescription, (long)error.code);
}
}
}
return 0;
}'42' -> 42
'' failed: The age is empty. (code 1)
'forty' failed: 'forty' is not a whole number. (code 2)
'7x' failed: '7x' is not a whole number. (code 2)
The rules of the pattern:
- Check the return value, not the error. Success is signalled by a non-
nil/YESresult; the error variable is only meaningful after a failure. - Callers may pass
NULLif they don't care about the details, so the method must checkif (error)before writing*error. - Pass the address of your variable:
&error.
Anatomy of an NSError
#import <Foundation/Foundation.h>
int main(void) {
@autoreleasepool {
NSError *underlying = [NSError errorWithDomain:@"com.example.disk" code:28
userInfo:@{NSLocalizedDescriptionKey: @"No space left on device."}];
NSError *error = [NSError errorWithDomain:@"com.example.export"
code:100
userInfo:@{
NSLocalizedDescriptionKey: @"The report could not be saved.",
NSLocalizedRecoverySuggestionErrorKey: @"Free up some space and try again.",
NSUnderlyingErrorKey: underlying,
@"fileName": @"q3-report.pdf",
}];
NSLog(@"domain: %@", error.domain);
NSLog(@"code: %ld", (long)error.code);
NSLog(@"description: %@", error.localizedDescription);
NSLog(@"suggestion: %@", error.localizedRecoverySuggestion);
NSLog(@"file: %@", error.userInfo[@"fileName"]);
NSError *cause = error.userInfo[NSUnderlyingErrorKey];
NSLog(@"caused by: %@ (%@ %ld)", cause.localizedDescription, cause.domain, (long)cause.code);
}
return 0;
}domain: com.example.export
code: 100
description: The report could not be saved.
suggestion: Free up some space and try again.
file: q3-report.pdf
caused by: No space left on device. (com.example.disk 28)
| Part | Purpose |
|---|---|
domain |
a string naming the subsystem, often reverse-DNS (NSCocoaErrorDomain, NSURLErrorDomain, NSPOSIXErrorDomain) |
code |
an integer identifying the error within the domain |
userInfo |
a dictionary with the message, recovery hints, the underlying error and your own keys |
Code numbers are only unique within a domain: always check the domain and the code together.
Methods that return BOOL
The same pattern with a BOOL result, in a class, and with the error propagated up to the caller:
#import <Foundation/Foundation.h>
@interface Vault : NSObject
- (BOOL)unlockWithPin:(NSString *)pin error:(NSError **)error;
- (BOOL)withdraw:(NSInteger)amount pin:(NSString *)pin error:(NSError **)error;
@end
@implementation Vault
- (BOOL)unlockWithPin:(NSString *)pin error:(NSError **)error {
if (![pin isEqualToString:@"2468"]) {
if (error) {
*error = [NSError errorWithDomain:@"Vault" code:401
userInfo:@{NSLocalizedDescriptionKey: @"Wrong PIN."}];
}
return NO;
}
return YES;
}
- (BOOL)withdraw:(NSInteger)amount pin:(NSString *)pin error:(NSError **)error {
if (![self unlockWithPin:pin error:error]) { // pass the same pointer down
return NO;
}
if (amount > 500) {
if (error) {
*error = [NSError errorWithDomain:@"Vault" code:402
userInfo:@{NSLocalizedDescriptionKey: @"Daily limit exceeded."}];
}
return NO;
}
NSLog(@"withdrew %ld", (long)amount);
return YES;
}
@end
int main(void) {
@autoreleasepool {
Vault *vault = [Vault new];
NSError *error = nil;
if (![vault withdraw:100 pin:@"0000" error:&error]) {
NSLog(@"error %ld: %@", (long)error.code, error.localizedDescription);
}
if (![vault withdraw:900 pin:@"2468" error:&error]) {
NSLog(@"error %ld: %@", (long)error.code, error.localizedDescription);
}
[vault withdraw:200 pin:@"2468" error:&error];
[vault withdraw:999 pin:@"2468" error:NULL]; // don't care about details
NSLog(@"done");
}
return 0;
}error 401: Wrong PIN.
error 402: Daily limit exceeded.
withdrew 200
done
In Apple's APIs
You'll see this signature on almost every Foundation method that touches the outside world (non-runnable sketch):
NSError *error = nil;
NSString *text = [NSString stringWithContentsOfFile:@"/tmp/notes.txt"
encoding:NSUTF8StringEncoding
error:&error];
if (!text) {
NSLog(@"Could not read the file: %@", error.localizedDescription);
}
NSData *json = [NSJSONSerialization dataWithJSONObject:payload options:0 error:&error];Tip: In Swift, methods following this pattern become
throwsfunctions automatically:let text = try String(contentsOfFile: path). That's another reason to follow the convention exactly.
Test yourself
How should you check whether a method using NSError ** failed?
- Check if error != nil
- Check the return value (NO or nil)
- Catch an exception
- Check error.code == 0
Why must the method write if (error) { *error = …; }?
- For speed
- Because callers may pass NULL
- To avoid a retain cycle
- Because error is weak
Which pair identifies a specific kind of NSError?
- code alone
- domain and code
- userInfo and code
- localizedDescription