Introduction and Overview

Hello there, eager learner! Today's programming adventure takes us into the deep world of back-end engineering. Specifically, we will focus on handling HTTP status errors 404 and 500 using Express.js.

In the world of the web, errors are unavoidable. Every time you've come across a page that says "Page Not Found" or "An unexpected error occurred" you've encountered a 404 or 500 error, respectively. Being able to handle these errors gracefully is a key skill for any web developer.

You'll learn how to customize how your web application responds to these errors. By the end of this lesson, you'll have the tools to not only understand these errors but also guide your users with useful error pages. Effective error handling enhances user experience and strengthens your application.

Understanding 404 and 500 Status Codes

Driving on the highway of the internet, whenever there's a hitch, HTTP status codes serve as our mile markers. Two frequent ones we encounter are 404: "Not Found" and 500: "Internal Server Error."

A 404 error means the browser requested a page that doesn't exist on the server. For instance, if you type www.notarealwebpagename.com into your browser, there's no page with that name, so you would get a 404 error!

A 500 error is a little more mysterious and indicates a problem with the server while processing the request. To explain in simpler terms, let's say you walk into a bakery to order cookies, but the oven breaks down. That is akin to a 500 error on a website!

Default Express.js Error Handling

Express.js is pretty smart when handling these two errors. By default, if a client requests a page that doesn't exist, it sends a 404 error in response. Similarly, if our server encounters an error while processing a request, Express.js will send a 500 status code.

Take a look at a basic Express server with default error handling below:

JavaScript
let express = require('express');
let app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

app.listen(3000, function () {
  console.log('App is listening on port 3000!');
});

If you try to visit a page that wasn't the home page (like /cookies), you would see an automatic 404 error. If there was any bug or syntax error, the server would send a 500 error.

While this default behavior is useful, we can make the user experience even better with tailored error messages. Let’s explore how to do that.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal