Reputation: 43
I started learning node.js and I am currently struggling with my middleware I wrote in node.js. It should be an Error handler. The problem is that I cannot access properties I defined inside constructor method. I get this error:
TypeError: Cannot read property 'response' of undefined notFound(/[irrelevant]/src/middleware/ErrorHandler.js:12:8)
This is my code:
ErrorHandler.js
class ErrorHandler {
constructor() {
this.response = {
success: false,
errorMessage: '',
status: 0
}
}
notFound(req, res, next) {
this.response.errorMessage = 'Not Found'
this.response.status = 404
res.status(404).send(this.response)
}
badRequest(req, res, next) {
this.response.errorMessage = 'Bad request'
this.response.status = 400
res.status(400).send(this.response)
}
}
module.exports = new ErrorHandler()
routes.api.js
// Import modules
const express = require('express')
const router = express.Router()
// Import controller
const contactController = require('../controllers/ContactController')
// Import error handler
const errorHandler = require('../middleware/ErrorHandler')
router.post('/contact', contactController.index)
// return 404 if no matching routes were found
router.use(errorHandler.notFound)
module.exports = router
maybe the code doesn't make any sense, I just need the answer what is causing the error, It's not the code for production purposes.
thank you in advance and have a nice day
Upvotes: 4
Views: 2633
Reputation: 332
Define your methods like this:
notFound = (req, res, next) => {}
Upvotes: 10
Reputation: 20441
You are passing in a function errorHandler.notFound
to the middleware. Next time it is called, it will not be bound to the object you exported.
So this
will not be your new ErrorHandler()
. In case you want to achieve that you can do two things: bind the method to the this
in the constructor.
Or use arrow function as mentioned by @Gogu. Arrow functions take this from their surroundings where they are defined.
Upvotes: 5