【问题标题】:Throwing errors to include http status codes抛出错误以包含 http 状态代码
【发布时间】:2022-11-02 03:15:15
【问题描述】:

我编写了一个 API,将服务与控制器分开。在我的服务函数中,我定义了简单的检查,如果遇到错误则抛出错误。我的控制器函数现在为每个抛出的错误返回一个 500 状态代码。当使用我使用的逻辑引发错误时,有没有办法指定 HTTP 代码?

控制器功能:

export const login = async (req: Request, res: Response) => {
    const { email, password } = req.body;

    try {
        const { accessToken, refreshToken } = await loginUser(email, password);

        res.cookie('jwt', refreshToken, { httpOnly: true, secure: true });

        return res.status(200).json({ accessToken });
    } catch (error) {
        return res.status(500).json({ error });
    }
};

服务功能:

export const loginUser = async (email: string, password: string) => {
    if (!email || !password) {
        throw new Error('All fields are required');
    }

    const user = await findUser(email);

    if (!user) {
        throw new Error('User does not exist');
    }

    const isValid = validPassword(password, user.password.salt, user.password.hash);

    if (isValid) {
        const { refreshToken, accessToken } = issueJWT(user._id);

        return { refreshToken, accessToken };
    } else {
        throw new Error('You entered the wrong password');
    }
};

【问题讨论】:

    标签: javascript node.js typescript express error-handling


    【解决方案1】:

    您可以创建一个接收消息、状态代码和数据的函数,并使用提供的信息创建错误,如下所示:

    module.exports.generateError = (message, statusCode, data) => {
        const error = new Error(message);
        error.statusCode = statusCode;
        error.data = data || {};
        error.error = true;
        return error
    }
    

    每次您都可以致电:

    throw generateError('You entered the wrong password',400);
    

    代替:

    throw new Error('You entered the wrong password');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 1970-01-01
      • 2013-11-20
      • 1970-01-01
      相关资源
      最近更新 更多