如何将错误的 `localizedDescription` 转换为 JSON 使用 Swift?

huangapple go评论55阅读模式
英文:

How to change error.localizedDescription to JSON by Swift?

问题

在Swift中,我从云函数中收到了错误。我像这样捕获了错误:

functions.httpsCallable("addMessage").call(["text": inputField.text]) { result, error in
  if let error = error as NSError? {
    if error.domain == FunctionsErrorDomain {
      let code = FunctionsErrorCode(rawValue: error.code)
      let message = error.localizedDescription
      let details = error.userInfo[FunctionsErrorDetailsKey]
    }
  }
}

消息以JSON格式从云函数获取,如下所示:

{"message":"text is required","status":"INVALID_ARGUMENT"}

如果我从云函数收到错误消息,而我想要将其显示给用户。首先,我尝试了以下代码:

let status = message["status"]

但在Xcode中我收到了 No exact matches in call to subscript 的错误消息。我该如何解决这个问题?

英文:

In Swift I got the error from Cloud Functions.
And I caught the error like this

functions.httpsCallable("addMessage").call(["text": inputField.text]) { result, error in
  if let error = error as NSError? {
    if error.domain == FunctionsErrorDomain {
      let code = FunctionsErrorCode(rawValue: error.code)
      let message = error.localizedDescription
      let details = error.userInfo[FunctionsErrorDetailsKey]
    }
  }
}

The message get like JSON format from Cloud functions.
{"message":"text is required","status":"INVALID_ARGUMENT"}

If I got the error message from Cloud functions, and I want to display to the user.
First I tried

let status = message["status"]

But I got No exact matches in call to subscript in xcode.
How do I resolve this problem?

答案1

得分: 2

error.localizedDescription 显然是一个 JSON 字符串,你需要对其进行反序列化。

let messageJSON = error.localizedDescription
let messageDictionary = try? JSONDecoder().decode([String: String].self, from: Data(messageJSON.utf8))
let message = messageDictionary?["message"] ?? ""
英文:

error.localizedDescription is obviously a JSON string, you have to deserialize it

let messageJSON = error.localizedDescription
let messageDictionary = try? JSONDecoder().decode([String:String].self, from: Data(messageJSON.utf8))
let message = messageDictionary?["message"] ?? ""

huangapple
  • 本文由 发表于 2023年2月8日 22:10:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75386985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定