Exception class for multiple JSON projects.
The library contains a single class – JSONException
.
This class has been extracted from the kjson-core
library in order to allow
it to be used independently of that library.
The class is very straightforward – to throw a JSONException
with a simple message:
throw JSONException("Something went wrong")
In this case, the message for the exception will be just the text supplied.
But a common requirement of error reporting in a JSON application is to identify the location within the JSON structure
where the error occurred.
For this purpose, the JSONException
takes an optional second parameter, a key
, specified as type Any?
.
If the key
is present, and the toString()
of its value is not empty, it is appended to the message with the word
"at
", as follows:
throw JSONException("Something went wrong", "/data/0/id")
This will produce the message: "Something went wrong, at /data/0/id
".
The example shows a JSON Pointer as the key, but the key can be anything with a useful string representation, for example:
throw JSONException("Something went wrong", "line $lineNumber")
This will produce a message like: "Something went wrong, at line 27".
The withCause()
function may be used to add a "cause
" (an underlying causative exception) to the JSONException
:
try {
doSomething()
}
catch (e: Exception) {
throw JSONException("Something failed").withCause(e)
}
This may be called once only, and should usually be called immediately after the creation of the exception.
The JSONException
class is open
, to allow it to be the base of a hierarchy of exception classes.
The key
property is also open
, so that derived classes may restrict the key
to a specific type.
For example:
class ParseException(
text: String,
override val key: Coordinates,
) : JSONException(text, key)
data class Coordinates(val line: Int, val column: Int) {
override fun toString(): String = "line $line, column $column"
}
The latest version of the library is 1.2, and it may be obtained from the Maven Central repository.
<dependency>
<groupId>io.kjson</groupId>
<artifactId>kjson-exception</artifactId>
<version>1.2</version>
</dependency>
implementation 'io.kjson:kjson-exception:1.2'
implementation("io.kjson:kjson-exception:1.2")
Peter Wall
2024-07-08