Skip to content

Instantly share code, notes, and snippets.

@acidtone
Last active March 10, 2021 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acidtone/f5a08d0f15e70c4ddf1d40571b9e0645 to your computer and use it in GitHub Desktop.
Save acidtone/f5a08d0f15e70c4ddf1d40571b9e0645 to your computer and use it in GitHub Desktop.
Express: Catch `404` errors

Express: Catch 404 Not Found errors

Prerequisites

  1. Express "Hello World!" app created.

Instructions

  1. Create a Hello World! express app or use an existing express project.

  2. Add support for 404 error handling. Add this custom middleware function after all other middleware that sends a request:

    app.use(function(request, response) {
      response.status(404);
      response.send('404: File Not Found');
    });
    • It's important this is the last middleware in your file just before the server is started. This function always returns a 404 response when it's invoked. In other words, if the request hasn't been sent by the time it reaches this function, it's a 404 by process of elimination.

Related Gists

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment