最近在写 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 && !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 && await user.passwordMatches(password.toString()) === false) {
throw unauthorized('Password must match to authorize a token generating');
} else if (refreshToken && refreshToken.user.emailAddress === emailAddress && Dayjs(refreshToken.expires).isBefore(Dayjs())) {
throw unauthorized('Invalid refresh token');
}
return {user, accessToken: user.token()};
}
1
zzetao 2021-06-08 22:18:19 +08:00
|
3
knives 2021-06-09 07:09:32 +08:00
没用过 express,查文档查到的: https://expressjs.com/zh-cn/guide/error-handling.html
按理说作为 node web 框架鼻祖,大家的处理方式应该都差不多,一个 middleware 就应该能搞定才是。 |
4
hongweiliuruige 2021-06-09 13:36:03 +08:00
nestjs 解君愁
|
5
ChevalierLxc 2021-06-09 13:49:18 +08:00
@knives 我第一个也想到的是 middleware
|
6
LawlietZ 2021-06-09 14:33:13 +08:00
中间件,不管 node 哪个框架
|
7
leopod1995 2021-06-09 16:27:56 +08:00
google `express global error handling`
https://expressjs.com/en/guide/error-handling.html |
8
xcstream 2021-07-19 17:15:22 +08:00
app.use(function(err, req, res, next) {
console.error(err.stack); res.status(500).send('Something broke!'); }); |