Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@interface ErrorFormatter : NSObject
@property (strong, nonatomic) NSError *error;
- (id)initWithError:(NSError *)error;
- (UIAlertView *)alert;
- (NSString *)message;
- (NSString *)title;
@end
#import "ErrorFormatter.h"
@implementation ErrorFormatter
- (id)initWithError:(NSError *)error {
self = [self init];
if (self) {
self.error = error;
}
return self;
}
- (UIAlertView *)alert {
return [[UIAlertView alloc] initWithTitle:[self title]
message:[self message]
delegate:nil
cancelButtonTitle:NSLocalizedString(@"controls.ok", nil)
otherButtonTitles:nil];
}
- (NSString *)message {
return [[NSBundle mainBundle] localizedStringForKey:[self keyWithType:@"message"]
value:[self defaultMessage]
table:nil];
}
- (NSString *)title {
return [[NSBundle mainBundle] localizedStringForKey:[self keyWithType:@"title"]
value:[self defaultTitle]
table:nil];
}
- (NSString *)defaultMessage {
if ([self.error localizedRecoverySuggestion]) {
return [self.error localizedRecoverySuggestion];
} else {
return [self.error localizedDescription];
}
}
- (NSString *)defaultTitle {
if ([self.error localizedFailureReason]) {
return [self.error localizedFailureReason];
} else {
return NSLocalizedString(@"errors.title", nil);
}
}
- (NSString *)keyWithType:(NSString *)type {
return [NSString stringWithFormat:@"errors.%@.%d.%@", self.error.domain, self.error.code, type];
}
@end
- (void)mapView:(MKMapView *)mapView didFailToLocateUserWithError:(NSError *)error {
ErrorFormatter *formatter = [[ErrorFormatter alloc] initWithError:error];
UIAlertView *alert = [formatter alert];
[alert show];
}
// Errors
"errors.title" = "Error";
"errors.kCLErrorDomain.0.title" = "Unknown Location";
"errors.kCLErrorDomain.0.message" = "Couldn't get a good reading. Long tunnel?";
"errors.kCLErrorDomain.2.title" = "No Internet";
"errors.kCLErrorDomain.2.message" = "Internet is unavailable or an error occured";
"errors.kCLErrorDomain.8.title" = "No results found";
"errors.kCLErrorDomain.8.message" = "";
"errors.kCLErrorDomain.9.title" = "No results found";
"errors.kCLErrorDomain.8.message" = "";
@tatey

This comment has been minimized.

Copy link
Owner Author

commented Oct 25, 2012

ErrorFormatter

Thin wrapper around NSError which lets you define custom strings or defaults to NSError localized strings.

Features

  • Optionally define titles and messages in Localizable.strings.
  • Missing titles default to localizedFailureReason or NSLocalizedString(@"errors.title", nil)
  • Missing messages default to localizedRecoverySuggestion or localizedDescription.

Screenshot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.