Handling Errors with try and catch

A crash is fine while you are learning. But a server that handles many users at once should not stop because one request had bad data. try/catch lets your program say what to do when something fails.

JSON.parse is a good example. When the text is not valid JSON, it does not return undefined. It throws an error:

function handle(text) {
  try {
    const record = JSON.parse(text);
    console.log(record.name);
  } catch (err) {
    console.log("Invalid JSON");
  } finally {
    console.log("request handled");
  }
}

handle('{"name":"Alice"}');
handle("not json");

Output:

Alice
request handled
Invalid JSON
request handled

The code in try runs first. With valid JSON, it runs to the end and the catch block is skipped.

With not json, JSON.parse throws. The rest of the try block is skipped at once, so no name is printed. The catch block runs instead, and the program keeps going.

The finally block runs in both cases. Use it for work that must always happen, like closing a file or logging that a request is done.

The err in catch (err) is the error object. It tells you what went wrong. err.name is the type of error, and err.message is the text:

try {
  JSON.parse("not json");
} catch (err) {
  console.log(err.name);
  console.log(err.message);
}

Output:

SyntaxError
Unexpected token 'o', "not json" is not valid JSON

Two habits keep try/catch useful.

Keep the try small. Put only the code that can fail inside it. If a big try also hides a typo somewhere else, your catch prints "Invalid JSON" for a problem that has nothing to do with JSON. Then you search in the wrong place.

Catch only what you can handle. Bad input, a missing file or a failed network call are good reasons to catch. A bug in your own code is not. Let it crash with a stack trace, so you can see it and fix it.

If no try catches an error, the program stops with the report you read in the previous lesson.

In the exercise, parse a line of JSON, print Invalid JSON if it fails, and print request handled in every case.