Saturday, 16 February 2019

Express: Throwing exceptions


There are two ways to throw an error in Express.
a.   Using throw statement
b.   Using next method

Setup the express project
Create a folder errorDemo. Open terminal, go inside ‘errorDemo’ directory and execute the command 'npm init -y'. It creates a default package.json file.

C:\Users\krishna\express_examples\errorDemo>npm init -y
Wrote to C:\Users\krishna\express_examples\errorDemo\package.json:

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

Step 2: Install express dependency by executing the below command.
npm install --save express

You should execute the above command from the directory, where your package.json file located. This command downloads the express module from Internet and update the package.json file with express dependency.

Using throw statement
You can throw the error using throw statement like below.

app.get('/welcome', (req, res, next) => {
         throw new Error("Unknown error while executing welcome request")
})

Create index.js file in the same place where your package.json located.


index.js
//Load express module
const express = require('express');

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

const port = 8080;

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'))

app.get('/welcome', (req, res, next) => {
 throw new Error("Unknown error while executing welcome request")
})

// 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}!`));

Execute the command ‘node index.js’.


Open the browser and hit the url ‘http://localhost:8080/welcome’


You can observe below things.
a.   Error stack trace is printed in browser body
b.   Error code 500 is returned. 500 represents internal server error.
c.    Below kind of stack trace is printed in console.
Error: Unknown error while executing welcome request
    at app.get (C:\Users\Public\errorDemo\index.js:13:8)
    at Layer.handle [as handle_request] (C:\Users\Public\errorDemo\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Public\errorDemo\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\Public\errorDemo\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Public\errorDemo\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Public\errorDemo\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\Public\errorDemo\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\Public\errorDemo\node_modules\express\lib\router\index.js:275:10)
    at expressInit (C:\Users\Public\errorDemo\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (C:\Users\Public\errorDemo\node_modules\express\lib\router\layer.js:95:5)

Using next method
You can throw the error using next method also.

app.get('/welcome', (req, res, next) => {
         next(new Error("Unknown error while executing welcome request"))
})

index.js
//Load express module
const express = require('express')

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

const port = 8080

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'))

app.get('/welcome', (req, res, next) => {
 next(new Error("Unknown error while executing welcome request"))
})

// 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}!`));

Open the browser and hit the url ‘http://localhost:8080/welcome’, you can observe the same behavior like  the first approach (Using throw statement).

Using throw statement vs throwing the error using next method
It is not good practice to throw an exception from asynchronous callbacks. If you throw an exception from route handler like next(), express handle the error in better way than throwing error directly.

Throwing error directly from asynchronous callback function
app.get('/welcome', (req, res, next) => {
         setTimeout(() =>{throw new Error("Unknown error while executing welcome request")}, 2000)
})

Above route, throws an error after 2 seconds. Update index.js like below.


index.js
//Load express module
const express = require('express')

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

const port = 8080

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'))

app.get('/welcome', (req, res, next) => {
 setTimeout(() =>{throw new Error("Unknown error while executing welcome request")}, 2000)
})

// 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}!`));

Execute ‘node index.js’. Open the browser and hit the url ‘http://localhost:8080/welcome’,


You can see completely weird message in the browser after 2 seconds.


And when you see the console, you can observe application terminated.

Application started listening on port 8080!
C:\Users\Public\errorDemo\index.js:13
        setTimeout(() =>{throw new Error("Unknown error while executing welcome request")}, 2000)
                         ^

Error: Unknown error while executing welcome request
    at Timeout.setTimeout [as _onTimeout] (C:\Users\Public\errorDemo\index.js:13:25)
    at ontimeout (timers.js:424:11)
    at tryOnTimeout (timers.js:288:5)
    at listOnTimeout (timers.js:251:5)
    at Timer.processTimers (timers.js:211:10)

Throwing error using route handler from asynchronous callback function
app.get('/welcome', (req, res, next) => {
         setTimeout(() =>{next(new Error("Unknown error while executing welcome request"))}, 2000)
})


index.js
//Load express module
const express = require('express')

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

const port = 8080

//When user hits the home page, then the message prints in browser.
app.get('/', (req, res) => res.send('Welcome to Node.js Programming'))

app.get('/welcome', (req, res, next) => {
 setTimeout(() =>{next(new Error("Unknown error while executing welcome request"))}, 2000)
})

// 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}!`));


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



You can see below messages in console.

Application started listening on port 8080!
Error: Unknown error while executing welcome request
    at Timeout.setTimeout [as _onTimeout] (C:\Users\Public\errorDemo\index.js:13:24)
    at ontimeout (timers.js:424:11)
    at tryOnTimeout (timers.js:288:5)
    at listOnTimeout (timers.js:251:5)
    at Timer.processTimers (timers.js:211:10)

Previous                                                 Next                                                 Home

No comments:

Post a Comment