# An example of an exception with data- attributes in JavaScript

Let the server generate an HTML code when loading the page, which stores the name, price and amount of the purchased product:

`<div id="product" data-product="apple" data-price="1000" data-amount="5"></div>`

Let's make a function that will take a reference to an item with a product and find the total cost of the product (multiply the price by the amount):

`function getCost(elem) { return elem.dataset.price * elem.dataset.amount; }`

We find the cost of our product:

`let product = document.querySelector('#product'); let cost = getCost(product); alert(cost);`

Let's now assume the following situation: due to some kind of failure on the server, it sent us a product in which there is no price or amount (or both at once), for example, like this:

`<div id="product" data-product="apple" data-price="1000"></div>`

If you now try to calculate the cost of the goods, the result will be NaN. Agree, not very informative.

It turns out that we need to somehow protect ourselves from the fact that the attributes we need will be missing. This can be done in two ways. The first way is to say that this is normal behavior and simply check with IF for the presence of the attributes we need:

`function getCost(elem) { if (elem.dataset.price !== undefined && elem.dataset.amount !== undefined) { return elem.dataset.price * elem.dataset.amount; } else { return 0; // let's return something like 0 or null or false } }`

The second option is to say that the absence of the `data-price` or `data-amount` attribute is an exception. In this case we will throw an exception:

`function getCost(elem) { if (elem.dataset.price !== undefined && elem.dataset.amount !== undefined) { return elem.dataset.price * elem.dataset.amount; } else { throw { name: 'ProductCostError', message: 'there is no price or amount for the product' }; } }`

Which of the two options is more appropriate to apply here is the choice of the programmer. It may treat the problem as normal script operation or as an exception.

Let us decide that the situation is exceptional. Then the code for retrieving the cost of the goods will look like this:

`let product = document.querySelector('#product'); try { let cost = getCost(product); alert(cost); } catch (error) { // we somehow react to an exception }`

Modify my code so that the `getCost` function throws two types of exceptions: if the price is missing and if the amount is missing. Think carefully about the names of these exceptions. In a `catch`-block, output different error messages for different exception types.

← →
↑
en ru