admin管理员组

文章数量:1279177

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

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

Share Improve this question edited Jul 3, 2021 at 10:20 nodejsnoob asked Jul 3, 2021 at 10:13 nodejsnoobnodejsnoob 431 silver badge4 bronze badges 1
  • perhaps you need to use this.notFound = this.notFound.bind(this); in your constructor - because how the function is being called . – Jaromanda X Commented Jul 3, 2021 at 10:21
Add a ment  | 

2 Answers 2

Reset to default 10

Define your methods like this:

notFound = (req, res, next) => {} 

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.

本文标签: javascriptCannot access class properties inside a methodStack Overflow