Nodejs 使用 express 和 typeorm 的项目如何实现 Global Error Handling

发布于 1周前 作者 gougou168 来自 nodejs/Nestjs

Nodejs 使用 express 和 typeorm 的项目如何实现 Global Error Handling

最近在写 nodejs,遇到了一个问题很迷幻。

如何在 controller/router 层来处理 services 或则 repository 层传递过来的错误呢?

现在是用 try catch 代码实在是太丑了。

我想实现的是类似于 Spring boot 的 controllerAdvise/ExceptionHandler 这种形式

网上搜了一圈也没啥好的办法,希望大佬们给点意见

例子如下:

router:


    async login(req: Request, res: Response) {
    try {
        const {user, accessToken} = await this.userRepository.findAndGenerateToken(req.body);

        const token = await AuthService.generateTokenResponse(user, accessToken);

        if (user.Role[0].role_id !== 3 && user.is_approval === false) {
            return ApiResultBean.errorMessage("User need to be approve!!");
        }

        if (token instanceof Error) {
            return ApiResultBean.error(req, token);
        }

        return ApiResultBean.success({token, user});

    } catch (error){

        // res.status(error.statusCode)
        console.log(error);
        if (error.output.payload) {
            return ApiResultBean.error(req, error,error.output.payload.message);
        }
        return ApiResultBean.error(req, error);

    }


}

repository 层:


       public async findAndGenerateToken(options: tokenOptions): Promise<{ user: User, accessToken: string; }> {
        const {username, emailAddress, password, refreshToken} = options;

        if (!emailAddress &amp;&amp; !username) {
            throw badRequest("An email address or username is required to generate a token");
        }

        let user;

        try {
            user = await this.findOne({
                relations: ['Role'],
                where: emailAddress ? {emailAddress: emailAddress} : {username: username}
            });
        }catch (error) {
            return error;
        }


        if (!user) {
            throw notFound('User not found');
        } else if (password &amp;&amp; await user.passwordMatches(password.toString()) === false) {
            throw unauthorized('Password must match to authorize a token generating');
        } else if (refreshToken &amp;&amp; refreshToken.user.emailAddress === emailAddress &amp;&amp; Dayjs(refreshToken.expires).isBefore(Dayjs())) {
            throw unauthorized('Invalid refresh token');
        }
        return {user, accessToken: user.token()};

}


回到顶部