Tuesday, 5 March 2019

express: Error handling middleware


Error handling middleware function takes four arguments.

Example
app.get('/welcome', (err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broken!');
});


As you see above example, first argument to error handling middleware is an error object, second one is request, third one is response object and last one is next object.

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

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

const port = 3000

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

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

app.get('/welcome', (err, req, res, next) => {
  console.error(err.stack);
  res.status(500).send('Something broken!');
});

// 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.

Open browser and hit the url ‘http://localhost:3000/welcome’, you can see below messages in console.

Application started listening on port 3000!
Error: Unknown error while executing welcome request
    at app.use (C:\Users\Public\nodeExamples\index.js:13:7)
    at Layer.handle [as handle_request] (C:\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\node_modules\express\lib\router\index.js:317:13)
    at C:\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\node_modules\express\lib\router\index.js:335:12)
    at next (C:\node_modules\express\lib\router\index.js:275:10)
    at expressInit (C:\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (C:\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\node_modules\express\lib\router\index.js:317:13)

    at C:\node_modules\express\lib\router\index.js:284:7




Previous                                                 Next                                                 Home

No comments:

Post a Comment