An Example of JSON Exception in JavaScript
Suppose a JSON with a product comes to us from somewhere in the external world:
let json = '{"product": "apple", "price": 1000, "amount": 5}';
let product = JSON.parse(json);
alert(product.price * product.amount);
You already know that the JSON.parse method
will throw an exception if the JSON is invalid.
Let's catch this exception:
try {
let json = '{"product": "apple", "price": 1000, "amount": 5}';
let product = JSON.parse(json);
alert(product.price * product.amount);
} catch (error) {
// somehow handle the exception
}
However, it might be that the JSON itself is valid, but does not contain the fields we need, for example, there is no price field:
let json = '{"product": "apple", "amount": 5}'; // no price
Let's say that this is also an exceptional situation and in such a case we will throw our own custom exception:
try {
let json = '{"product": "apple", "amount": 5}';
let product = JSON.parse(json);
if (product.price !== undefined && product.amount !== undefined) {
alert(product.price * product.amount);
} else {
throw {
name: 'ProductCostError',
message: 'product is missing price or quantity'
};
}
} catch (error) {
// somehow handle the exception
}
Now the catch block will receive two types
of exceptions: either the JSON is completely invalid,
and then it will be an exception of type SyntaxError,
or the JSON is valid but does not contain the required
fields, and then it will be an exception of type
ProductCostError.
Let's catch these types of exceptions in the catch block:
try {
let json = '{"product": "apple", "amount": 5}';
let product = JSON.parse(json);
if (product.price !== undefined && product.amount !== undefined) {
alert(product.price * product.amount);
} else {
throw {
name: 'ProductCostError',
message: 'product is missing price or quantity'
};
}
} catch (error) {
if (error.name == 'SyntaxError') {
alert('Invalid product JSON');
} else if (error.name == 'ProductCostError') {
alert('Product is missing price or quantity');
}
}
Suppose a JSON of the following kind comes to you:
let json = `[
{
"name": "user1",
"age": 25,
"salary": 1000
},
{
"name": "user2",
"age": 26,
"salary": 2000
},
{
"name": "user3",
"age": 27,
"salary": 3000
}
]`;
Check this JSON for general correctness during parsing, and after parsing, check that the result is an array, not something else. If the result is not an array - throw an exception.