Let JSON with a product come to us from somewhere:
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) {
// we somehow react to an exception
}
However, it may be that the JSON itself is correct, but doesn't 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 exception and in this case we will throw our 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: 'there is no price or amount for the product'
};
}
} catch (error) {
// we somehow react to an exception
}
Now the catch
-block will receive two
types of exceptions: either the JSON is not
correct at all, in which case there will be
an exception like SyntaxError
, or the
JSON is correct, but does not contain the
fields we need, in which case there will
be an exception like 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: 'there is no price or amount for the product'
};
}
} catch (error) {
if (error.name == 'SyntaxError') {
alert('Invalid JSON of the product');
} else if (error.name == 'ProductCostError') {
alert('Product has no price or amount');
}
}
Let JSON come to you like this:
let json = `[
{
"name": "user1",
"age": 25,
"salary": 1000
},
{
"name": "user2",
"age": 26,
"salary": 2000
},
{
"name": "user3",
"age": 27,
"salary": 3000
}
]`;
Check this JSON for the correctness as a whole when parsing, and after parsing - check that the result is an array and not something else. If the result is not an array, throw an exception.