AppDividend
Latest Code Tutorials

Express Error Handling Example Tutorial

547

Get real time updates directly on you device, subscribe now.

Express Error Handling Example Tutorial is today’s leading topic. One of the most crucial things in a building web applications are error handling. The system will depend on many services, databases, as well as consumers of those services, the unexpected becomes expected. Databases will fail, services become unavailable, server timeout. So your consumers won’t be calling your endpoints with the parameters you would expect. To prepare your application for such scenarios, you need to handle errors appropriately.

Error Handling refers to how Express catches and processes errors that occur both synchronously and asynchronously. Express error handling middleware is a powerful tool for consolidating your HTTP error response logic.

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Join the program

Express Error Handling Example Tutorial

Let us take a simple example of error handling.

app.get('/customers', async function(req, res) {
  let customers;
  try {
    customers = await db.collection('Customer').find().toArray();
  } catch (error) {
    res.status(500).json({ error: error.toString() });
  }
  res.json({ customers });
});

Here, we have defined the endpoint called ‘/customers.’ So when any consumer tries to access the route ‘/customers,’ it will go through the try-catch block. If any error occurs then, it will immediately throw an exception and error will be returned otherwise the users will be returned.

The above pattern works well if you have one or two endpoints, but if you’re maintaining dozens of endpoints, then you are going to lose your mind quickly. Let’s say you have decided that HTTP response code 503 is more appropriate than HTTP 500; so you are going to have to change that for every single endpoint.

#Catching Express Errors

It is essential to assure that Express catches all the errors that occur while running route handlers and middleware. Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it.

Errors that occur in synchronous code inside route handlers and middleware require no extra work. If synchronous code throws an error, then Express will catch and process it. For example:

app.get("/", function (req, res) {
  throw new Error("Opps!! Something went wrong"); // Express will catch this on its own.
});

For errors returned from asynchronous functions invoked by route handlers and middleware, you must pass them to the next() function, where Express will catch and process them. For example:

app.get("/", function (req, res, next) {
  fs.readFile("/file-does-not-exist", function (err, data) {
    if (err) {
      next(err); // Pass errors to Express.
    }
    else {
      res.send(data);
    }
  });
});

#Writing error handling Middleware

Express middleware is divided into different types based on the number of arguments your middleware function takes. The middleware function that takes four arguments which are classified as “error handling middleware,” and will only get called if an error occurs. Define the error-handling middleware functions in the same way as other middleware functions are defined, except error-handling functions, have four arguments instead of three: (err, req, res, next). For example:

app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something went wrong!!');
});

You define error-handling middleware last, after other app.use() and routes calls; for example:

const bodyParser = require('body-parser');
const methodOverride = require('method-override');

app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(function (err, req, res, next) {
  console.error(err.stack);
  res.status(500).send('Something went wrong!!');
});

The only way to report errors to Express for use with error handlers is using the third argument to standard middleware, the next() function.

Now, let us take a practical example.

#1: Create Express Project

Create an express project folder.

mkdir errorexpress && cd errorexpress

Open the project in VSCode.

code .

Now, initialize the package.json file.

npm init -y

Install express using the following command.

npm install express --save

# or

yarn add express

#2: Setup Express server.

Okay, now inside the root,  create one file called server.js.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;


app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Now, add the exception code.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

app.get('*', function(req, res, next) {
  setImmediate(() => { 
    next(new Error('Ohh!! Something went wrong')); 
  });
});

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Save the file and go to the terminal and start the node server.

node server

 

Related Posts
1 of 17

Express Error Handling Example Tutorial

Now go to the browser and hit this URL: http://localhost:3000

You will see the JSON response with an error message. So this is how we can write a middleware that throws an error.

#Use With Async/Await in Error Middleware

Express was mostly written 2011-2014, before ES6, and it still lacks a good answer for how to handle the async/await keywords. We can write the above code in async/await manner.

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

function wrapAsync(fn) {
  return function(req, res, next) {
    fn(req, res, next).catch(next);
  };
}

app.get('*', wrapAsync(async function(req, res) {
  await new Promise(resolve => setTimeout(() => resolve(), 50));
  throw new Error('Oppss!! Something went wrong');
}));

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Here, with a little helper function, you can tie async/await errors in with Express error handling middleware. Remember that async functions return promises, so you need to make sure to .catch() any errors and pass them to next():

// server.js

const app = require('express')();
const PORT = process.env.PORT = 3000;

function wrapAsync(fn) {
  return function(req, res, next) {
    fn(req, res, next).catch(next);
  };
}

app.get('*', wrapAsync(async function(req, res) {
  await new Promise(resolve => setTimeout(() => resolve(), 50));
  throw new Error('Oppss!! Something went wrong');
}));

app.use(function(error, req, res, next) {
  res.json({ message: error.message });
});

app.listen(PORT, () => {
  console.log('Server is running at PORT',PORT);
});

Finally, Express Error Handling Example Tutorial is over. Thanks for taking.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.