Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access class properties inside a method

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

like image 437
nodejsnoob Avatar asked Oct 21 '25 15:10

nodejsnoob


1 Answers

Define your methods like this:

notFound = (req, res, next) => {} 
like image 126
Gogu Gogugogu Avatar answered Oct 23 '25 04:10

Gogu Gogugogu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!