Question

I'm trying to add error codes to one of my project like this:

typedef enum {
    FSChatErrorChatManagerInUse = 101,
    FSChatErrorFailedToRetrieveHeader = 202,
    FSChatErrorFailedToGetCount = 303,
} FSChatErrorCode;

Then, send:

NSError * err = [NSError errorWithDomain:@"Failed To Get Count"
                                    code:FSChatErrorFailedToGetCount
                                userInfo:nil];

So when notified of an error, you can see what kind it is:

if (err.code == FSChatErrorFailedToGetCount) {
    // do stuff
}

Question

Is there some sort of standard error code syntax or numbering I should follow? I'm having a hard time finding a reference.

Was it helpful?

Solution

This page has a nice discussion of this subject:

Like exit status codes, an NSError -code signals the nature of the problem. These status codes are defined within a particular error domain, in order to avoid overlap and confusion. These status codes are generally defined by constants in an enum.

For example, in the NSCocoaErrorDomain, the status code for an error caused by NSFileManager attempting to access a non-existant file is 4, as defined by NSFileNoSuchFileError. However, 4 in NSPOSIXErrorDomain refers to a POSIX EINTR, or "interupted function" error.

So, since you're using your own error domain, you can create whatever error codes you want. By the way, in your example you seem to be misusing the domain value: it's not meant to contain an error message.Use userInfo[NSLocalizedDescriptionKey] for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top