Skip to content
This repository has been archived by the owner on Sep 19, 2018. It is now read-only.

Error Handling

mdmathias edited this page Jan 19, 2016 · 7 revisions

Common Errors in Parsing JSON

Parsing JSON can be error prone. Two sorts of errors are especially common: 1) the JSON doesn't have the key that you are looking for, and 2) you are trying to subscript the JSON with an index that is out of bounds.

Freddy helps you mitigate these and other errors by leveraging Swift's native mechanism for error handling. This means that Freddy provides you with useful information should your JSON throw you a curveball.

JSON's Errors

Freddy's JSON enumeration defines an ErrorType called Error that catalogues the errors that you may encounter while parsing a JSON instance.

extension JSON {
    public enum Error: ErrorType {
        case IndexOutOfBounds(index: Swift.Int)
        case KeyNotFound(key: Swift.String)
        case UnexpectedSubscript(type: JSONPathType.Type)
        case ValueNotConvertible(type: Any.Type)
    }
}

Below, we run through common examples of handling an error while working with JSON.

Before we begin, let's imagine some JSON:

{
    "people": [
        {
            "Matt": 32
        },
        {
            "Drew": 33
        }
    ]
}

Here, we have JSON with a key "people" that points to an array of dictionaries, where each dictionary gives a person's name and their age.

Index Out of Bounds

  • IndexOutOfBounds(index: Swift.Int) - the IndexOutOfBounds case tracks errors for when you try to index an JSON.Array, but have supplied an index that is not within the array's range. The case's associated value will correspond to the index that is out of bounds.

For this example, imagine that you want to grab the third index in the array associated with the key "people" in the JSON. The trouble is, there is no third index...

let json = ["people": [ ["Matt": 32], ["Drew": 33] ] ] as JSON
do {
    let thirdDictionary = try json.dictionary("people", 2)
} catch JSON.Error.IndexOutOfBounds(let badIndex) {
    print("Index out of bounds: \(badIndex)")
} catch {
    // Handle the catch all
}

Key Not Found

  • KeyNotFound(key: Swift.String) - the KeyNotFound case is thrown when a JSON instance is subscripted for a key that is not present in the JSON. The associated value for this case will be the key that was not found.

Let's pretend that we are expecting to find data within the above JSON for our friend "Sarah". Since this key is not present within the JSON, we will get the KeyNotFound error.

do {
    let thirdDictionary = try json.dictionary("people", 2)
    let sarahAge = try json.int("Sarah")
} catch JSON.Error.IndexOutOfBounds(let badIndex) {
    print("Index out of bounds: \(badIndex)")
} catch JSON.Error.KeyNotFound(let badKey) {
    print("Key not found: \(badKey)")
} catch {
    // Handle the catch all
}

Unexpected Subscript

  • UnexpectedSubscript(type: JSONPathType.Type) - this case is thrown when you attempt to subscript a JSON instance with a subscript of some unexpected type. For example, this error will be thrown if you try to subscript a JSON.Dictionary with an Int. The associated value provides you with the type the JSON was not expecting.

For this example, let's just assume that we got our stars crossed and are trying to subscript "Drew"'s age as a String.

Value Not Convertible

  • ValueNotConvertible(type: Any.Type) - the ValueNotConvertible error is thrown when you attempt to convert a JSON instance into a type that it be cannot be converted to. For example, you will get this error if you try to convert an Int value into a String (e.g., json.string("age")). The associated value describes the type mismatch.
Clone this wiki locally