Recover

Go makes it possible to recover from a panic by using the recover built-in function. A recover can stop a panic from aborting the program and let it continue with execution instead.

An example of where this can be useful: a server wouldn’t want to crash if one of the client connections exhibits a critical error. Instead, the server would want to close that connection and continue serving other clients. In fact, this is what net/http does by default for HTTP servers.

This function panics.

function mayPanic() {
  throw new Error("a problem");
}

recover must be called within a deferred function. When the enclosing function panics, the defer will activate and a recover call within it will catch the panic.

The return value of recover is the error raised in the call to panic.

function main() {
  // Similar to defer and recover in Go, we can use a try-catch block in JavaScript
  try {
    mayPanic();
  } catch (err) {
    // This is analogous to recovering from a panic
    console.log("Recovered. Error:\n", err.message);
  }

  console.log("After mayPanic()");
}

main();

This code will not terminate execution abruptly because of the error in mayPanic. The execution of main stops at the point of the error and resumes in the catch block.

To run the program, just execute it with node.js:

$ node recover.js
Recovered. Error:
 a problem
 After mayPanic()

Now that we understand how to handle errors gracefully in JavaScript, let’s learn more about the language.