Home > Software engineering >  NodeJS redirect from handler
NodeJS redirect from handler

Time:12-17

We need to direct from a Log Handler, this handler is being called from a route and I tried to use many ways, this is the latest that makes more sense but still it seems to not work. I would like no matter what, this direct always happens if it's called.

router.get('/AccessDenied', utils.CheckAuthenticated, function(req,res) {
    try {
      let ContentTitle = "Abcd1234"
    } catch (error) {
      CustomErrorLog(error, metadata)
    }
})

The function CustomErrorLog is:

const logger = require("../services/logger")
const uuid = require("uuid");

module.exports = {
    CustomErrorLog: (error, metadata) => {
        return (req, res, next) => {
            let correlationId = uuid.v4()
            metadata["correlation_id"] = correlationId;
            logger.error(error, metadata);
            res.redirect('/error/'   errorId)
        }
    }
}

I tried many different approaches and none seems to work. Any help is appreciated.

CodePudding user response:

It looks like you're trying to use the CustomErrorLog function as a middleware function, but it's not set up correctly for that. Middleware functions are called with three arguments: req, res, and next. Your CustomErrorLog function is missing the next argument, and it's also not returning the middleware function.

To fix this, you can update the CustomErrorLog function to accept three arguments and return the middleware function:

module.exports = {
    CustomErrorLog: (error, metadata) => {
        return (req, res, next) => {
            let correlationId = uuid.v4()
            metadata["correlation_id"] = correlationId;
            logger.error(error, metadata);
            res.redirect('/error/'   errorId)
        }
    }
}

Then, you can use the CustomErrorLog function as a middleware in your route like this:

router.get('/AccessDenied', utils.CheckAuthenticated, function(req,res) {
    try {
      let ContentTitle = "Abcd1234"
    } catch (error) {
      CustomErrorLog(error, metadata)(req, res, next)
    }
})

This will ensure that the CustomErrorLog function is called with the correct arguments and that it behaves as a middleware function.

  • Related