Article image Building a Basic REST API with NodeJS and ExpressJS: Error Handling

10.8. Building a Basic REST API with NodeJS and ExpressJS: Error Handling

Page 73 | Listen in audio

10.8. Building a Basic REST API with NodeJS and ExpressJS: Error Handling

NodeJS and ExpressJS are two powerful tools you can use to create REST APIs. A REST API, or Representational State Transfer, is a style of software architecture that uses a set of protocols and standards to build web applications. In this section, we'll learn how to create a basic REST API with NodeJS and ExpressJS and how to handle errors.

Setting the environment

Before we start, we need to make sure we have NodeJS and npm (Node Package Manager) installed on our system. If you don't have them yet, you can download them from the official NodeJS website. After installation, you can verify that they are installed correctly by running the following commands in the terminal:

$ node -v
$ npm -v

Next, we need to install ExpressJS, which is a web framework for NodeJS. You can install ExpressJS using npm with the following command:

$ npm install express

Creating the REST API

First, let's create a new file called 'app.js'. This will be our main file where we will configure our REST API. In the 'app.js' file, let's start by importing the ExpressJS:

const express = require('express');

Next, let's create a new instance of Express:

const app = express();

Now, let's define some routes for our API. For example, let's create a GET route to '/users' that returns a list of users:

app.get('/users', (req, res) => {
  res.json({ users: ['John', 'Jane', 'Bob'] });
});

Finally, let's make our application listen to port 3000:

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Error handling

Error handling is a crucial part of any application. In ExpressJS, you can handle errors using error middleware. An error middleware is a function that takes four arguments: (err, req, res, next).

You can define an error middleware as follows:

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

This error middleware will catch any error that occurs in the application and will log the error stack to the console, and then send a response with status 500 and the message 'Something broke!'.

It is important to note that the error middleware must be defined after all other routes and middleware, because it will only catch errors that occur in the middleware and routes that are defined before it.

In addition, you can create custom error middleware to handle different types of errors in different ways. For example, you can create an error middleware to handle validation errors and another to handle authentication errors.

Conclusion

In this chapter, we learned how to create a basic REST API with NodeJS and ExpressJS and how to handle errors. ExpressJS makes it very easy to create REST APIs and offers many useful features such as error middleware that allow us to handle errors effectively.

In the next chapter, we'll learn how to add authentication to our API and how to secure our routes with JWT (JSON Web Tokens).

Now answer the exercise about the content:

What is a REST API and what tools are used to create it?

You are right! Congratulations, now go to the next page

You missed! Try again.

Article image Building a Basic REST API with NodeJS and ExpressJS: Authentication and Authorization

Next page of the Free Ebook:

74Building a Basic REST API with NodeJS and ExpressJS: Authentication and Authorization

5 minutes

Earn your Certificate for this Course for Free! by downloading the Cursa app and reading the ebook there. Available on Google Play or App Store!

Get it on Google Play Get it on App Store

+ 6.5 million
students

Free and Valid
Certificate with QR Code

48 thousand free
exercises

4.8/5 rating in
app stores

Free courses in
video, audio and text