Open In App

How to return an error back to ExpressJS from middleware ?

Last Updated : 27 Oct, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to cover the problem of “How to return errors/exceptions to ExpressJS using middleware”. Error handling refers to catching and processing errors that might occur both synchronously and asynchronously. Fortunately, ExpressJS comes with its own error handler, so you don’t need to write your own. 

Middleware functions have access to the request object and the response object and also the next function in the application request-response lifecycle.  if synchronous code throws an error (inside route handlers and middleware), then express will catch it and process it automatically on its own, you don’t need to do anything extra.  

Example 1: The below route is throwing an error, and ExpressJS will catch it on its own (synchronous code).

Javascript




const express = require("express");
const app = express();
app.get("/", function (req, res) {
    throw new Error("BROKEN");
});
app.listen(3000);


Output: 

The terminal of VS Code

Example 2: The above example is of the synchronous code, but how the ExpressJS will handle errors when it comes asynchronously. The example below shows you the same.

Javascript




const fs = require("fs");
const express = require("express");
const application = express();
  
application.get("/", function (req, res, next) {
    fs.readFile("/file-not-found", function (err, data) {
        if (err) {
            next(err); // Passing errors to Express.
        } else {
        // sending back the response if everything works well.
            res.send(data); 
        }
    });
});
  
application.listen(3000);


Output: 

The terminal of VS Code

Example 3: The error-handling middleware is given below; it takes four arguments instead of three.

Javascript




const fs = require("fs");
const express = require("express");
  
const application = express();
  
application.get("/", function (req, res) {
  fs.readFile("/file-not-found");
});
  
application.use((err, req, res, next) => {
  console.error(err.stack);
  res
    .status(500)
    .send(
      "<h1 style='color:green;text-align:center;'>GfG<h1/><br />" +
        "<pre style='text-align:center;'>
            Something broke!<pre/>"
    );
});
  
application.listen(3000);


Output: 

In the browser window + console

This way you could return errors/exceptions in ExpressJS using middleware, and you can also send back entire HTML files showing error 404 or error 500 as per your style. 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads