Error to NSError conversion

I’m passing an error from one app to another via XPC.

public enum MyCoolError: Error {
    case some
    case thing
    case text(value: String)
}

In the source app the error looks like this when printed:

error: text(value: "Hello, World")

If I first coerce it to NSError it is good:

nserror: AppName. MyCoolError. text (value: "Hello, World")

This is how the error looks in another app:

error: Error Domain=AppName.MyCoolError Code=0 " (null)"

NSError coerced form is not any better:

nserror: Error Domain=AppName.MyCoolError Code=0 " (null)"

Is there a trick to augment this behaviour so I could still see the error payload (“Hello, World” in this case) in another process? Without reverting to NSError that is.

1 Like

Conform your error to CustomNSError protocol.

2 Likes

A bit to expand the answer, I’ve been bitten by this implicit conversion to NSError several times, and my rule of thumb, if you operate with any system that works with NSError in one way or another (and talking about Apple ecosystem that’s always the case), is to provide this conformance to mostly any error defined in Swift. This allows to avoid implicit and unexpected error codes assumptions, keep relevant information and provide more meaningful description is the error appears in logs or reached user interface. It also reduces bugs in case you happen to rely on equatability of NSError. I would like to say that the ultimate solution for majority of cases is to work with concrete errors, but so far we have only gotten to typed errors recently, and other ways like Result isn’t always convenient to work with.

1 Like