Working tips, encapsulating if and Exception

In our work, there is often such logic, which is to judge whether a parameter is legal, and throw an exception if it is not legal, and then return after being caught by the global exception.

This article uses the springboot diary system I wrote as a blueprint, and is modified on the basis of existing projects. The source code download address and tutorial are at the end of the article.

For example, there is such a registration method in the controller:

@RequestMapping("register")
public Result register(@RequestBody User user){
    if(StrUtil.isEmpty(user.getUserName())){
        throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("用户名不允许为空!"));
    }
    if(StrUtil.isEmpty(user.getPassword())){
        throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("密码不允许为空!"));
    }
    //检查用户名是否重复
    if(userService.getByUserName(user.getUserName()) != null){
        throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("用户名"+user.getUserName()+"重复!"));
    }
    //拼装userBean
    user.setUid(redisServiceImpl.getIncr("userId")); //redis自增ID
    user.setPassword(SecureUtil.md5(user.getPassword() + salt));
    user.setCreateTime(DateUtil.now());
    user.setUpdateTime(DateUtil.now());
    userService.save(user);
    return Result.success();
}

The point is this:

if(StrUtil.isEmpty(user.getUserName())){
   throw new BizException(ExceptionCodeEnum.ERROR_PARAM.setDesc("用户名不允许为空!"));
}

We are used to using if to judge the legality of a parameter first, and throwing an exception if it is not legal.

There is no problem in doing so, but if there are many such judgments, the code will become bloated.

How to simplify it?

We can change from the previous reverse thinking to positive thinking, which is the so-called assertion .

For example, this logic is to throw an exception when it detects that the user name is empty. Then we can change this logic to: I require that this username must be non-empty, otherwise an exception will be thrown.

Let's write a validation class and method.

/**
 * 通用校验工具类
 */
@Slf4j
public class VerifyBusinessUtil {

    /**
     * 断言
     * @param judge
     * @param error
     */
    public static void checkArguments(boolean judge,String error){
        if(!judge){
            log.error("{}", error);
            throw new BizException(ExceptionCodeEnum.ERROR_PARAM,error);
        }
    }

}

This code is a general verification tool class, which contains a method called checkArguments, which receives two parameters: a judgment condition judge of type boolean and an error message error of type String.

Inside the method, a log object is first defined using Slf4j annotations to record error messages. Then, if the judge is false, that is, the judgment condition is not satisfied, a BizException will be thrown, and the error message error and the exception code ExceptionCodeEnum.ERROR_PARAM will be passed into the exception together.

This method is mainly used to verify whether the input parameters are legal. If not, an exception will be thrown and an error message will be printed.

Then you can rewrite the previous if statement

@RequestMapping("register")
public Result register(@RequestBody User user){
    VerifyBusinessUtil.checkArguments(!StrUtil.isEmpty(user.getUserName()),"用户名不允许为空!");
    VerifyBusinessUtil.checkArguments(!StrUtil.isEmpty(user.getPassword()),"密码不允许为空!");
    VerifyBusinessUtil.checkArguments(userService.getByUserName(user.getUserName()) == null,"用户名"+user.getUserName()+"重复!");
   
    //拼装userBean
    user.setUid(redisServiceImpl.getIncr("userId")); //redis自增ID
    user.setPassword(SecureUtil.md5(user.getPassword() + salt));
    user.setCreateTime(DateUtil.now());
    user.setUpdateTime(DateUtil.now());
    userService.save(user);
    return Result.success();
}

Is it much more refreshing?

Haha, this is a method that most companies will encapsulate. It is very easy to use, and it does have its reasons.

If this is the first time you see this style of writing, then use it quickly! ~

Source code download

I completed this case in  the springboot diary system  , and those who need the source code can directly clone the project.

https://gitee.com/skyblue0678/diary

 

Guess you like

Origin blog.csdn.net/weixin_39570751/article/details/131085595