Plan for things going wrong

INPUT · Slides

Throwing an error yourself

01 / 05

Even an odd value carries on

Hand a function a value you were not expecting and JavaScript says nothing in particular. It calculates with it and shows it as it is.

In the example below a negative number has arrived as an age, and it goes through with nothing happening. If you cannot stop it here, it turns into a meaningless result on some line far away and the cause cannot be traced.

const tellAge = (age) => {  console.log(`${age} years old`);};tellAge(-3);

Result

-3 years old

02 / 05

Throw one yourself with throw

Write throw new Error("message") and you can cause an error on the spot. In the message, write in your own words what is wrong and why it is trouble.

Once it reaches the throw line, nothing after it runs. Without a catch to catch it, the program stops right there.

const checkAge = (age) => {  if (age < 0) {    throw new Error("age must be 0 or more");  }  console.log(`${age} years old`);};checkAge(12);checkAge(-3);

Result

12 years old
Error: age must be 0 or more

03 / 05

Catch it on the calling side

A thrown error can be caught by the calling side's try / catch. Just as you did in the last lesson.

The message of the error the catch caught holds the sentence you wrote, as it was. So writing it in words that reach the reader helps you later.

const checkAge = (age) => {  if (age < 0) {    throw new Error("age must be 0 or more");  }  console.log(`${age} years old`);};try {  checkAge(-3);} catch (error) {  console.log(error.message);}

Result

age must be 0 or more

04 / 05

The sooner it fails, the closer the cause

Where you write the throw is where you noticed the odd value. Checking and turning it away at the function's door is clearest of all.

Let it carry on and the strange value slips through the sums and comes out on a line far away as "I cannot see why this is the result". Fail it close by and the cause is close by too.

const buy = (count) => {  if (count <= 0) {    throw new Error("count must be 1 or more");  }  console.log(`${count * 120} yen`);};try {  buy(0);} catch (error) {  console.log(error.message);}

Result

count must be 1 or more

05 / 05

The message is for the reader

A message that only says "no good" tells you nothing when you read it later. Put in what is wrong and why it is trouble.

  • does not reach … "error"
  • reaches … "the name is empty"

Stopping is not spite; it is kindness so nobody suffers later. Right — let us throw some errors ourselves.