Racing Horse
Racing Horse

Reputation: 21

How to bubble error object across several methods?

This is more of a C question but here it goes.

I've a method that receives as a parameter the address of a pointer to an NSError object. Now, that method is buried several levels deep in the class hierarchy and I need to make the error object bubble all the way to the top.

I could return the error object on each method but I'd rather do it the Cocoa way and return a boolean while passing the error object as a parameter.

How can I do this?

Upvotes: 1

Views: 202

Answers (1)

Peter Hosey
Peter Hosey

Reputation: 96363

I could return the error object on each method but I'd rather do it the Cocoa way and return a boolean while passing the error object as a parameter.

The Cocoa way is the Boolean direct return with a by-reference (i.e., through pointer) return of the error value, like so:

NSError *error = nil;
if ([foo trySomething:bar error:&error]) {
    //Success!
} else {
    //Failure!
}

(Alternatively, trySomething:error: may return an object, in which case you treat that object as the Boolean return: non-nil is true/succeeded, nil is false/failed.)

To make this chainable, each method (except the outermost) should have an error-pointer parameter, and use that in its implementation:

- (void) trySomething:(MyBar *)bar error:(out NSError **)outError
    if ([bartender restock:bar error:outError]) {
        //Success!
    } else {
        //Failure!
    }
}

You can combine both approaches, catching the error object in your own local variable in order to customize or wrap it in the failure case before storing the customized/wrapper error at the error-return pointer for your caller to receive.

Upvotes: 1

Related Questions