ambientlight
ambientlight

Reputation: 7332

Swift 2: Error handling: throw: How to pass an object with an error?

How to pass the userInfo reference object when throwing an error in Swift2?

Something like this would be good:

guard let refIDString = memberXMLElement.attributes["ref"] else {
     throw OSMVectorMapDescriptionError.ElementDoesntContainRequiredAttributes(userInfo:memberXMLElement)
}

And then:

catch OSMVectorMapDescriptionError.ElementDoesntContainRequiredAttributes {
  (userInfo:AnyObject) in
      //do stuff                 
 }

But errors are enums, we do can specify like here, but how to catch it?

public enum OSMVectorMapDescriptionError:ErrorType {
    case ElementDoesntContainRequiredAttributes(userInfo:AnyObject)
}

Upvotes: 1

Views: 292

Answers (1)

Mario Zannone
Mario Zannone

Reputation: 2883

Assuming that you don't need someLevel, you can define

public enum OSMVectorMapDescriptionError:ErrorType {
   case ElementDoesntContainRequiredAttributes(userInfo: ...)
}

use your guard unchanged

guard let refIDString = memberXMLElement.attributes["ref"] else {
    throw OSMVectorMapDescriptionError.
              ElementDoesntContainRequiredAttributes(userInfo:memberXMLElement)
}

and

catch OSMVectorMapDescriptionError.
          ElementDoesntContainRequiredAttributes(let userInfo) {
  //do stuff using userInfo              
}

Upvotes: 1

Related Questions