简体   繁体   English

错误处理程序中间件不处理错误

[英]Error handler middleware doesn't handle the errors

Started using this npm package to avoid all try catches blocks and promises.开始使用此 npm package以避免所有尝试捕获块和承诺。 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.如果我用 try catch 包装异步 function ,它会用代码 23505 捕获错误 - 所以基本上,处理程序应该解决问题,但它没有。 Also, the error: UnhandledPromiseRejectionWarning: Unhandled promise rejection.此外,错误: UnhandledPromiseRejectionWarning: Unhandled promise 拒绝。 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().此错误源于在没有 catch 块的情况下抛出异步 function 内部,或拒绝未使用.catch() 处理的 promise。 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在未处理的 promise 拒绝时终止节点进程.. 是的,我明白我需要解决这个错误,但这就是我使用中间件 + package 来避免 all.then.catch 的原因

In my main file - app.js at the very top I have required this package:在我的主文件 - 最顶部的 app.js 中,我需要这个 package:

require("express-async-errors");

Here I call the function which fails(I'm doing it on purpose now)在这里我调用 function 失败(我现在是故意这样做的)

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这里我调用 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
    };

It seems the middleware function doesn't return the (eventually rejected) promise, so the package's code can never see it.似乎中间件 function 没有返回(最终被拒绝)promise,所以包的代码永远看不到它。

It's likely that at your call to registerService (or somewhere higher up in your call stack) you are missing an await keyword.在您调用registerService (或调用堆栈中更高的位置)时,您可能缺少await关键字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM