How to throw error from services and repositories in nodeJS app following repository pattern

Viewed 893

I am developing an API in NodeJS, expressJS and I am following repository pattern. So there are controllers, services and repositories. Now, by the rules of repository pattern, My controllers, services and repositories are like this. These are just for demonstration purpose, actual code is different from this.

authController.js

export const loginController = async (req, res, next) => {
    const user = await authServices.login(req.body);
    if (user.error) {
        res.error(user.errorBody)
    }
    else {
        return res.success({ code: 200, message: "Logged in succesfully", data: user });
    }

}

authServices.js

export const loginServcies = async (loginDetails) => {
    const user = await userRepository.login(loginDetails);
    if (!user) {
        return {
            error: true, errorBody: {
                code: 422, message: 'User doesnot exist', errors: null
            }
        }
    }
    else if (!user.active) {
        return { error: true, errorBody: { code: 403, message: 'User not active', errors: null } };
    }
    else if (user) {
        return user;
    }
}

userRepository.js

export const userRepository = async (loginDetails) => {
    let user;
    try {
        user = await user.find({ where: { user: loginDetails.user } })
    }
    catch (error) {
        return { error: true, errorBody: { code: 500 } }
    }
}

Now the problem I am facing is I am repeating the code and returning the error from repo => services => controller. What I want is, to throw the error from anywhere either it be repository or services. As per the express documentation, we can use a global middleware in our app.js and pass the error to the next function like next(err), and express will automatically handle that.

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

but as next() function is not available in our services and repositories, how can I handle and throw the errors? In the above example, I just passed two errors from services to controllers but in a practical case, there could be many, so I will repeat a lot of code, that I don't want to do

1 Answers

In controller, surround service call in a try-catch block and pass error to the next function.

Then, you can throw errors in service and repository functions and manage them in errorHandler middleware.

Related