0

Further to this question's answer. For me, an error occurs when using this code. I want to know exactly what kind of error occurs from the catch block. You're supposed to do this by catching the error's type, but I don't see error types enumerated in the jsonObject documentation

do {
    let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
    print(json)
} catch {
    print("error") //which error?
}

Is there a way to do this in swift, or how can I find the exceptions an object throws?

bobobobo
  • 64,917
  • 62
  • 258
  • 363
  • 2
    Swift automatically gives you an error object as input to the `catch` clause so do `print(error)` to get a proper error message (the error handling in the linked answer is really bad) – Joakim Danielson Mar 15 '21 at 14:12
  • @JoakimDanielson Wow! Magic -- shouldn't that cause a compiler error? – bobobobo Mar 15 '21 at 14:15
  • Like I said it is given to you (synthesised) so it exists without having to be declared – Joakim Danielson Mar 15 '21 at 14:19
  • Not related to your question but `[String: AnyObject]` is the dictionary format prior to Swift 3. It should be `[String: Any]` – Leo Dabus Mar 15 '21 at 17:01

1 Answers1

2

In the catch section the error is available for you, so instead of the string your are printing right now, you can access the error object:

do {
    let json = try JSONSerialization.jsonObject(with: data!) as! Dictionary<String, AnyObject>
    print(json)
} catch {
    print(error)
}
πter
  • 1,899
  • 2
  • 9
  • 23
  • It works! But `error` wasn't declared anywhere, so how? – bobobobo Mar 15 '21 at 14:17
  • It is the way the `catch` block is working. It automatically gives you the error which was thrown. – πter Mar 15 '21 at 14:21
  • 1
    Do not use *Or a bit shorted version of the error* (`.localizedDescription`) with `JSONSerialization` and `JSONDecoder`. Instead of the real error you get a generic meaningless message – vadian Mar 15 '21 at 17:20
  • @vadian agree. Edited my answer – πter Mar 15 '21 at 17:38