当在swift中发现错误时,我应该打印什么?[重复]

问题描述 投票:0回答:1
catch let error {
    print(error)
    print("xxxxxxxxxxxxxxx")
    print(error.localizedDescription)
}

打印。

typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "期望解码Array,但发现了一个字典。", underlyingError: nil)) xxxxxxxxxxxxxxx 数据无法被读取,因为它的格式不正确。

对我来说,信息

debugDescription: "期望解码Array,但发现了一个字典" "Expected to decode Array but found a dictionary instead."

要比文本中的 error.localizedDescription. 那为什么我不能做这样的事情。print(error.debugDescription) 它不能编译。

swift
1个回答
1
投票

debugDescription定义在协议CustomDebugStringConvertible中。所以你必须先投递error.Context(codingPath: [_JSONKey())。

if let customDebugStringConvertible = error as? CustomDebugStingConvertible {
    print(customerDebugStringConvertible.debugDescription)
}

至于要打印什么 对于日志记录来说,最翔实的版本是简单的print(error)。


1
投票

你可以给你的错误描述!

enum MyErrors: String, Error {
   case badError = "I think it went wrong here"
   case evilError = "This should have never happened"
}

func test() throws {
   if Bool.random() {
      throw MyErrors.badError
   } else {
      throw MyErrors.evilError
   }
}

do {
   try test()
} catch let error {
    if let myError = error as? MyErrors {
        print(myError.rawValue)
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.