NodeJs — Creating a generic error handling
Hello guys!
Today we’re going to see how to create a global error handling in NodeJs with no need to implement many try/catch blocks to your code.
Access the example code on Github
We recomend you to also take a look into this YouTube video
Steps
To start we will create the entire initial structure of a project for a better understanding.
REQUIREMENTS:
- Nodejs
- Npm
- Express
- Add a new folder to your computer and name it “generic-error-handler”
- Access the new folder, open your terminal and type:
npm init -y
yarn init -y
3. Then we will add some packages to our project
npm i express
yarn add express
4. Open the package.json file and add the following command to the “scripts” session:
"dev": "node app.js"
5. Add the file app.js to your project and type the following code, this will be our initial configuration
const express = require('express')
const app = express()
// enabling our app to work with JSON
app.use(express.json());
// adding a default route to our application
app.get('/', (req, res, next) => {
res.send({
message: 'Hello world'
})
})
app.listen(3001, () => {
console.log('App listening at 3001')
})
With this you’ll be able to see the result below
6. Add a file called “example.controller.js”, then copy and paste the code below
class ExampleController {
static throwErrorMethod(req, res) {
throw new Error('Some error that can happen during the app execution');
}
}
module.exports = ExampleController;
7. Back to the app.js, we will add the code responsible for “wrap” our routes, and handle the errors
// this will be our wrapper
const use = fn => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
// this is the route we're going to "wrap"
app.get('/example', use(exampleController.throwErrorMethod));
// this will be our middleware, our ErrorHandler
app.use(function(err, req, res, next) {
res.status(500).send({
message: err.message
})
});
8. Finally run your code. =)
npm run dev
yarn dev
You can test your routes using postman app: