Wednesday, 20 February 2019

Node.js: Express: Create custom error page


It is always good to display custom error page on error conditions. For example, I had written simple application, that displays welcome message in home page.

index.js
const express = require('express')

const app = express()

const port = 8080

app.get('/', (req, res) => res.send('Welcome to home page'))

app.listen(port, () => console.log(`Application started listening on port ${port}!`));


Run index.js using the command ‘node index.js’. Open the url ‘http://localhost:8080/’, in browser, you can see below message in browser.



Try to access the url ‘http://localhost:8080/welcome’, you can see default message from node.js.




But in many cases, we want to display custom error page that gives more information to the user.

How can we build custom error message?
Add below statement to the end of all the routes and middlewares.

app.use((req, res) => {
         return res.send('Your request does not match to any of our services')
})

If no request matches to existing routes and middlewares, it is fallback to this.

index.js

const express = require('express')

const app = express()

const port = 8080

app.get('/', (req, res) => res.send('Welcome to home page'))

app.use((req, res) => {
 return res.send('Your request does not match to any of our services')
})

app.listen(port, () => console.log(`Application started listening on port ${port}!`));


Run index.js and open the url ‘http://localhost:8080/welcome’ in browser, you can see below message.


In real world applications, it is nicer to send the custom error page (That contains error status code, message, stack trace if the application is running in development mode) than the plain message.

We can do that by using some custom template engine.

Follow step-by-step procedure to build complete working application.

Step 1: Create new folder ‘errorPageDemo’.
Go inside errorPageDemo and execute the command npm init -y. it creates package.json file.


C:\Users\Public\errorPageDemo>npm init -y
Wrote to C:\Users\Public\errorPageDemo\package.json:

{
  "name": "errorPageDemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

Step 2: We need to add the express and http-errors dependency to our project.

Execute below commands from the directory where your package.json located.

npm install --save http-errors
npm install --save express


After executing above two commands, package.json file is updated like below.

{
  "name": "errorPageDemo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4",
    "http-errors": "^1.7.1"
  }

Step 2: Create a folder views and define the file ‘errorPage.ejs’.


errorPage.ejs

<html>

 <head>
  <title>Express and EJS integration</title>
  <meta charset="utf-8">
  
  <style>
     h3 {
    font-family: georgia, serif; 
    font-size: x-small;
    color : red
   }

 </style>

 </head>
 
 <body>
  <h3>
   Message : <%= message %> <br /> <br />
   
   Error Code <%= errorCode %> <br /> <br />
   
   Trace: <%= stackTrace %>
  </h3>
 </body>
</html>

Step 3:
Create index.js file in the same directory where your package.json is located.


index.js

//Load express module
const express = require('express');
const path = require('path');
const createError = require('http-errors')

//Put new Express application inside app variable
const app = express();

//Set views property and views engine
app.set("views", path.resolve(__dirname, "views"));
app.set("view engine", "ejs");

const port = 8080;

app.get('/', (req, res) => {
 res.send('Welcome to node.js programming')
})


app.use((req, res, next) => {
 return next(createError(404, 'Request not implemented (or) file not found'))
});

app.use((err, req, res, next) => {
 
 // Other than 404, we are returning internal server error (500)
 errorStatus = err.status || 500
 
 errorStackTrace = req.app.get('env') === 'development' ? err : {}
 errorMessage = err.message || "Can't process the request"

 res.locals.status = errorStatus
 
 return res.render("errorPage", {
  message: errorMessage,
  errorCode: errorStatus,
  stackTrace : stringifyError(errorStackTrace, null, '\t')
 })

})

// Start the express application on port 8080 and print server start message to console.
app.listen(port, () => console.log(`Application started listening on port ${port}!`));

var stringifyError = function(err, filter, space) {
  var plainObject = {};
  Object.getOwnPropertyNames(err).forEach(function(key) {
    plainObject[key] = err[key];
  });
  return JSON.stringify(plainObject, filter, space);
};


Run index.js, and hit the url ‘http://localhost:8080/welcome’, you can see below page.



Previous                                                 Next                                                 Home

No comments:

Post a Comment