Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error handler middleware doesn't handle the errors

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
    };

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading