Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - Error Handling While Processing JSON



Handling error is a crucial aspect of any robust application. Groovy provides groovy.json.JsonException specially to handling error which can occur while parsing an exception using JsonSlurper object to parse a JSON string. Apart from parsing errors, we should handle other scenarios using standard try-catch functionality of Groovy. Following are common use cases with corresponding Exception where errors can come up while processing a JSON.

  • JsonException − To handle parsing errors while parsing JSON using JsonSlurper.

  • MissingPropertyException − To handle a access to non-existing key of object parsed from JSON.

  • IndexOutOfBoundsException − To handle a invalid index in case of JSON array.

  • NullPointerException − To handle issue while accessing properties of a null object

  • NumberFormatException − To handle error while converting a value while using JsonBuilder.

Example - Handling Parsing errors while processing JSON

While using JsonSlurper it is good practice to wrap the parseText method under try-catch block for JsonException as shown in example below −

Example.groovy

import groovy.json.JsonSlurper
import groovy.json.JsonException

def badJsonString = '''
{
  "name": "Alice",
  "age": 30,
  "city": New York // Missing quotes
}
'''

def jsonSlurper = new JsonSlurper()

try {
    def jsonData = jsonSlurper.parseText(badJsonString)
    println jsonData 
} catch (JsonException e) {
    println "Parsing error while processing JSON: ${e.getMessage()}"
}

Output

When we run the above program, we will get the following result.

Parsing error while processing JSON: Unable to determine the current character, it is not a string, number, array, or object

The current character read is 'N' with an int value of 78
Unable to determine the current character, it is not a string, number, array, or object
line number 5
index number 45
  "city": New York // Missing quotes
..........^

Example - Handling errors while creating JSON

While using JsonBuilder, we may face exceptions while processing the data programming, It is advisable to put try-catch with relevant exception as shown in example below −

Example.groovy

import groovy.json.JsonBuilder

def data = [name: "Charlie", age: "fortyfive"] 

try {
    def builder = new JsonBuilder()
    builder {
        name data.name
        age data.age.toInteger() // toInteger will throw error
    }
    println builder.toPrettyString()
} catch (NumberFormatException e) {
    println "Error: Age is not a valid number - ${e.getMessage()}"
}

Output

When we run the above program, we will get the following result.

Error: Age is not a valid number - For input string: "fortyfive"

Example - Handling errors while processing JSON data after parsing

It is always a good practice to handle scenarios even after parsing JSON like missing property, null object acess, invalid index access and so as shown in example below −

Example.groovy

import groovy.json.JsonSlurper

def jsonString = '''
{
   "name": "A;ice",
   "age": 25,
   "hobbies": ["reading books","listening music"]
}
'''

def slurper = new JsonSlurper()
def person = slurper.parseText(jsonString)

try {
   println "Name: ${person.name}"
   println "City: ${person.city}" 
   // MissingPropertyException can occur if hobbies in not present
   println "First hobby: ${person.hobbies[0]}"
   // IndexOutOfBoundsException may occur if index is out of bound
   println "Second hobby: ${person.hobbies[1]}" 
   // NullPointerException in case address is null
   println "Address zip: ${person.address.zip}" 
} catch (MissingPropertyException e) {
   println "Property missing - ${e.getProperty()}"
} catch (IndexOutOfBoundsException e) {
   println "Invalid Index - ${e.getMessage()}"
} catch (NullPointerException e) {
   println "Null Propery Accessed - ${e.getMessage()}"
}

Output

When we run the above program, we will get the following result.

Name: A;ice
City: null
First hobby: reading books
Second hobby: listening music
Null Propery Accessed - Cannot get property 'zip' on null object
Advertisements