1

Started using this npm package to avoid all try catches blocks and promises. And it feels that error handler is 'sleeping' all the time. Maybe anyone have any insights what I've done wrong in this case? If I wrap the async function with try catch, it catches the error with code 23505 - so basically, the handler should solve the issue, but it doesn't. Also, the error: UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection.. Yeah I get the point that I need to solve this error, but that's the reason why I use the middleware + package to avoid all .then.catch

In my main file - app.js at the very top I have required this package:

require("express-async-errors");

Here I call the function which fails(I'm doing it on purpose now)

const {hashPassword} = require("../utils/bcryptUtils");
const {registerUserDao} = require("../dao/usersDao");

const registerService = async (requestUser) => {
    const registrationPayload = {
        email: requestUser.email.toLowerCase(),
        password: await hashPassword(requestUser.password),
        phone_number: requestUser.phone_number,
        first_name: requestUser.first_name.charAt(0).toUpperCase() + requestUser.first_name.slice(1),
        last_name: requestUser.last_name.charAt(0).toUpperCase() + requestUser.last_name.slice(1),
    };

    // If I wrap this await function in try catch I can handle the error here
    await registerUserDao(registrationPayload);

};

module.exports = {
    registerService
};

And the dao:

const database = require("../database/knex");

const registerUserDao = async (userPayload) => {
    return database("users").insert(userPayload).returning("*");

};

module.exports = {
    registerUserDao
};

Error handler middleware:

const {StatusCodes} = require("http-status-codes");

const errorHandlerMiddleware = (err, req, res, next) => {
    console.log(`error activated! ` + err);
    let customError = {
        statusCode: err.statusCode || StatusCodes.INTERNAL_SERVER_ERROR,
        message: err.message || "Something went wrong.. Please try again later."
    };

    if (err.code === "23505") {
        customError.statusCode = 409;
        customError.message = "Duplicate error. Client with provided data already exsists";
    }

    return res.status(customError.statusCode).json({message: customError.message});
};

module.exports = errorHandlerMiddleware;

And for sure I added it to very end of my routes:

// middlewares
const errorHandlerMiddleware = require("./middlewares/errorHandlerMiddleware");

// routes
app.use("/api/v1/auth", authRouter);

app.use(errorHandlerMiddleware);

Here I call registerService

    const {registerService} = require("../services/authServices");
    const {StatusCodes} = require("http-status-codes");
    // Yup I see the issue now! Been missing await before
    const registerController = async (req, res) => {
        const response = registerService(req.body);
        res.status(StatusCodes.CREATED).json({response});
    };
    
    module.exports = {
        registerController
    };
3
  • @CherryDT What I thought is that the error middleware should handle the rejected promise? Shouldn't it? Commented Jan 26, 2022 at 9:20
  • @CherryDT, your information about Koa was useful, never heard about it before. Gonna take a deep look at it anyway, thank you! The most strangest part about the package is that previously I had pretty same code and it worked without any issues. Cleared cache, updated packages, still I do occur the same issue. Commented Jan 26, 2022 at 9:29
  • @CherryDT you are genius! I've been missing the await all the time.... Commented Jan 26, 2022 at 9:32

1 Answer 1

2

It seems the middleware function doesn't return the (eventually rejected) promise, so the package's code can never see it.

It's likely that at your call to registerService (or somewhere higher up in your call stack) you are missing an await keyword.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.