扩展错误处理程序

时间:2017-03-12 17:11:42

标签: ios swift

我有扩展,我在单独的swift文件中声明,我用它来处理用户填写注册信息时的错误。但是,在我的调试中返回String,我想使用一些警报或imageViews来显示取决于错误。问题是我不知道如何在此扩展的返回部分传递IBOutlet或创建警报。例如,如果firstName为空,则在firstName文本字段附近将显示红色圆圈警报(imageView)。也许我处理错误的架构是错误的,或者可能有办法怎么做?

如果你给我一个正确的方向来寻找解决方案,我将非常感激。

这是扩展名

import UIKit

enum RegistrationErrors: Error {
    case invalidFirstName
    case invalidLastName
    case invalidCountry
}

extension RegistrationErrors: CustomStringConvertible {
var description: String {
    switch self {
    case .invalidFirstName:
        return "FirstName cannot be empty"

    case .invalidLastName:
        return "LastName cannot be empty"

    case .invalidCountry:
        return "Country cannot be empty"
    }
}

}

以下是我使用此扩展程序的代码

func registrationUser(firstName: String, lastName: String, country: String) throws -> (String, String, String)   {
    guard let firstName = firstNameTextField.text , firstName.characters.count != 0 else {
        throw RegistrationErrors.invalidFirstName
    }

    guard let lastName = lastNameTextField.text , lastName.characters.count != 0 else {
        throw RegistrationErrors.invalidLastName
    }

    guard let country = countryTextField.text , country.characters.count != 0 else {
        throw RegistrationErrors.invalidCountry
    }

    return (firstName, lastName, country)
}

// MARK: Actions

@IBAction func continueBtnTapped(_ sender: Any) {

    do {
        let (firstName, lastName, country) = try registrationUser(firstName: firstNameTextField.text!, lastName: lastNameTextField.text!, country: countryTextField.text!)
        if let currentUser = FIRAuth.auth()?.currentUser?.uid {
            DataService.instance.REF_BASE.child("users").child("profile").setValue(["firstName": firstName, "lastName": lastName, "country": country, "userId": currentUser])
            performSegue(withIdentifier: "toUsersList", sender: self)
        }
    } catch let error as RegistrationErrors {
        print(error.description)
    } catch {
        print(error)
    }
}

2 个答案:

答案 0 :(得分:0)

您的RegistrationErrors CustomStringConvertible扩展并不是一个坏主意。我想你会想要在do..catch块中处理向用户显示错误。

您可以捕获以下特定错误:

do {
  ... try registerUser(...)
} catch RegistrationErrors.invalidFirstName {
  view.invalidFirstName()
} catch ...

您也可以像处理一样注册错误时捕获错误,然后处理交换机中的特定错误:

// ...
catch let error as RegistrationErrors {
  print(error)
  switch error {
    case .invalidFirstName:
        view.invalidFirstName()
    // ...
  }

答案 1 :(得分:0)

不是从Error派生错误,而是从LocalizedError派生它。这允许您提供localizedDescription属性,如果您愿意,甚至可以在以后对其进行本地化:

do {
    throw RegistrationErrors.invalidLastName
} catch {
    let problem = error.localizedDescription
    // "Last name cannot be empty"
    // ... now present your alert ...
}

这成为了捕获点的错误localhost/postmyproject

define( 'WP_SITEURL', 'localhost/postmyproject' );
define( 'WP_HOME', 'localhost/postmyproject' );

这是一种通用的解决方案。不需要特殊代码;捕获点不必知道错误的任何额外属性,并且如果捕获点是Objective-C代码,它甚至可以工作,因为本地化描述只会延续到NSError版本中。