Why is error handling important?


#1

Question

Why is error handling important?

Answer

Error handling might seem like a trivial part of programming, for example, at first sight, if we see this:

app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broke!');
});

it does not seem that helpful, but in implementation it is. We might have heard of Testing Driven Development, it is the practice of creating functional tests that will run our code with close to real life input to make sure it works properly, yet it is not real life and there will always be a thousand things out of our control (and some overseen or unthought) that can make our app or server go wrong. that is why we have error handlers it does not only let us know as developers why something didn’t work, we can use them to fix that error and we can use them to let our user know what has just happened, by providing a friendly message, redirecting them to a working page, or a mix of both.

Not all errors are our fault, as per server-side goes, that is why we have status codes. In the previous example, a 500 error is sent, which does mean that the issue is either in the server or the server connection, but if in our routes, we have the proper functionality and checks, yet the user receives a 400 or 404 (very common) it means that for the first one, we can wash our hands and blame the user because somewhere in their request something is incorrect in type or missing and therefore it is a bad request, and for the second one it is nobody’s fault, the information or data requested just does not exists, therefore it is not found, those two are also considered errors and it is important to have handlers because otherwise the server or page most likely will simply crash rendering everyone just simply confused.

So handling errors allow us to provide feedback even though there was a problem while giving the option to do something else or something about it, and for developers, it can give us the information we need to see if the error is something that we need to fix .