Reporting handled exceptions

In order to quickly understand and fix errors, it is often helpful to send exceptions that have been handled by your application to Bugsnag, with additional diagnostic data that is specific to the error.

Basic usage

If you would like to send handled exceptions to Bugsnag, you can pass any NSError object to Bugsnag’s notifyError method:

NSError *error = nil;
BOOL success = [[NSFileManager defaultManager] removeItemAtPath:@"//invalid/file" error:&error];
if (!success) {
    [Bugsnag notifyError:error];
}
do {
    try FileManager.default.removeItem(atPath:"//invalid/file")
} catch {
    Bugsnag.notifyError(error);
}

Instances of NSException can be sent using the notify method:

@try {
    [NSJSONSerialization dataWithJSONObject:badlyFormattedJson options:0 error:nil];
} @catch (NSException* exception) {
    [Bugsnag notify:exception];
}
let exception = NSException(name:NSExceptionName(rawValue: "NamedException"),
                            reason:"Something happened",
                            userInfo:nil)
Bugsnag.notify(exception)

This will create and send a report for a “handled” error, with the default severity “warning”.

Customizing diagnostic data

You can send handled exceptions with diagnostic data or other customizations by passing a callback block as an argument to notify and notifyError.

The block receives an event object as a parameter which can be used to add or amend the data sent to your Bugsnag dashboard. You can also return false from the callback to prevent the event being sent at all:

[Bugsnag notifyError:error block:^BOOL(BugsnagEvent *event) {
    // Add extra information
    [event addMetadata:@"Acme Co." withKey:@"name" toSection:@"account"];
    [event addMetadata:@(YES) withKey:@"paying_customer" toSection:@"account"];

    // Increase severity
    event.severity = BSGSeverityError;

    // Return `NO` if you'd like to stop this error being reported
    return YES;
}];
Bugsnag.notifyError(error) { event in
    // Add extra information
    event.addMetadata("Acme Co.", key: "name", section: "account")
    event.addMetadata(true, key: "paying_customer", section: "account")

    // Increase severity
    event.severity = .error 

    // Return `false` if you'd like to stop this error being reported
    return true
}

See Customizing error reports for more information about the properties and methods available in an Event object.