【问题标题】:Error handling in non-throwing function in SwiftSwift 中非抛出函数的错误处理
【发布时间】:2017-12-10 12:38:35
【问题描述】:

我在处理非抛出函数(如重写方法、委托方法或数据源方法)中的错误时遇到问题。我只是想出了记录错误,你知道这不是一个好的错误处理策略。还有其他方法,方法等吗?谢谢。

编辑:

enum SomethingError : Error{
    case somethingFailed
}

var anObject : AnObject?

........
........


public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      guard let anObject = anObject else{
            throw SomethingError.somethingFailed
            //and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return"
        }

      .....
      .....

      return cell
}

你不能这样做,因为 :collectionView:cellForItemAt:indexPath 不是一个抛出函数,它必须返回一个单元格。我怎样才能在这里发现错误?这就是问题。仅通过日志记录?

编辑:我知道我可以使用if let我想接住/扔掉;在此处处理错误。

【问题讨论】:

  • 一个具体的例子会很有帮助。
  • 定义“错误”,因为它没有抛出错误?你有方法的例子吗?
  • 不能 throw cellForItem 出现错误,但你可以 catch 抛出错误。基本上避免委托和数据源方法中的任何可以退出范围的代码。

标签: swift error-handling


【解决方案1】:

您不能在没有明确要求的协议实现中传播错误。

你可以throw/catch他们在同一个实现中或者简单地调用一个方法来处理错误。在您的示例中,您可以像这样使用throw/catch

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      do {

          guard let anObject = anObject else {
              throw SomethingError.somethingFailed
              //and maybe return unprocessed cell but you cannot return anything after "throw", or you cannot "throw" after "return"
      } catch SomethingError.somethingFailed {
          // handle the error here
      }

      .....
      .....

      return cell
}

只有一个函数,它会是这样的:

func handleError() {
    // handle error
}

public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell throws{
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", at: index)

      guard let anObject = anObject else{
            handleError()
            return
        }

      .....
      .....

      return cell
}

有关 swift 错误处理的更多信息,您可以阅读:The Swift Programming Language: Error Handling

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 2016-10-10
    • 2022-10-14
    • 2016-02-19
    • 2022-07-25
    • 1970-01-01
    相关资源
    最近更新 更多