如何从swift中的Error获取键值

时间:2017-02-28 10:20:55

标签: swift swift3 nserror

如何以最佳方式从此错误结果中获取消息值。我很多但从来没有得到这个价值,所以请帮帮我

 BUYClient.sharedClient.createCustomer(with: credentials) { (customer : BUYCustomer?,token:  BUYCustomerToken?, error :Error?) -> Void in
                if customer != nil{
                    print(token ?? "kuch nahi aaya")
                    print(customer?.fullName ?? "kuch nahi aaya")
                }
                let customer = error.debugDescription

                print("value===\(customer)")
            }

结果:

     value===Optional(Error Domain=BUYShopifyErrorDomain Code=422 "(null)" UserInfo={errors={
            customer =     {
                email =         (
                                {
                        code = taken;
                        message = "has already been taken";
                        options =                 {
                            "rescue_from_duplicate" = 1;
                            value = "y@gmail.com";
                        };
                    }
                );
            };
        }})

1 个答案:

答案 0 :(得分:3)

要访问错误的userInfo,您必须将Error投射到经典NSError,之后您可以像字典一样访问userInfo

let nserror = error as! NSError
if let errors = nserror.userInfo["errors"] as? [String: NSObject],
   let customer = errors["customer"] as? [String: NSObject],
   let email = customer["email"] as? [[String: NSObject]]
{
    let message = email[0]["message"]
}