Chris G
Chris G

Reputation: 123

Receiving Swift throw-n custom error type in objective C

Im throwing an error in Swift that I'm trying to consume in ObjC. Works except when I complicate the situation by using a custom error type.

Here is the type Im throwing:

@objc public final class MyNetworkResponse: NSObject, Error {
...
}

To throw in swift Im simply doing:

throw resp

where resp is of type MyNetworkResponse.

In C resp appears to be bridged to NSError. Im unable to convert it/cast it back to the MyNetworkResponse type - is this possible, and if so how?

Im wondering if when I declare the @objc type there is a way to override the exception type?

Upvotes: 0

Views: 520

Answers (1)

DarkDust
DarkDust

Reputation: 92306

Errors in Objective-C are always assumed to be NSError objects and thus Swift automatically translated them. You can control how this is done by implementing the CustomNSError protocol, but you will still end up with a new object, an NSError. You cannot cast an NSError to your object.

But, you can somewhat work around it. One idea:

  • Implement CustomNSError on your MyNetworkResponse. In the errorUserInfo you can basically put in whatever info your object holds.
  • Implement MyNetworkResponse.init?(nsError: NSError) which looks at an NSError instance and tries to convert it back to your object. Check the error domain, then grab your data from the userInfo dictionary.

There's several variations, come up with whatever suits you, but the basic gist is that you need to put your error infos into the NSError's userInfo.

Upvotes: 1

Related Questions