我应该以哪种方式处理异常?

时间:2019-12-30 13:21:14

标签: java spring boot

所以我制作了一个Spring Boot应用程序,我想知道应该如何处理异常:

首先:具有一个自定义异常,如果两个密码不匹配,则将其引发并使用@ExceptionHandler对其进行处理:

public class PasswordsNotMatchException extends Exception {
    public PasswordsNotMatchException(final String message) {
        super(message);
    }
}

@PostMapping("/change-password") 
public String postChangePassword(@RequestParam Map<String, String> body) throws PasswordsNotMatchException { 

        userService.changePassword(body.get("email"), body.get("password"), body.get("matchesPassword")); 
        return "login";
}

@Override
    public void changePassword(String email, String password, String matchesPassword) throws PasswordsNotMatchException {
        User user = userRepository.findByEmail(email);

        if (password.equals(matchesPassword)) {
            user.setPassword(passwordEncoder.encode(password));
            user.setMatchingPassword(user.getPassword());
            user.setConfirmationToken(null);

            userRepository.save(user);

        }  else throw new PasswordsNotMatchException("Passwords do not match!");    
    }


@ExceptionHandler(PasswordsNotMatchException.class) 
public ModelAndView handleError() { 
     ModelAndView mav = new ModelAndView("changePassword");
     mav.addObject("email", body.get("email")); mav.addObject("passwordsNotMatch", true);

     return mav; 
}

第二个:将“ changePassword”方法从void更改为Boolean,如果密码匹配则返回true,否则返回false:

@Override
public Boolean changePassword(String email, String password, String matchesPassword) {
    User user = userRepository.findByEmail(email);

    if (password.equals(matchesPassword)) {
        user.setPassword(passwordEncoder.encode(password));
        user.setMatchingPassword(user.getPassword());
        user.setConfirmationToken(null);
        user.setIsEnabled(true);

        userRepository.save(user);

        return true;
    }

    return false;
}

并根据true或false返回值更改控制器的行为:

@PostMapping("/change-password")
    public ModelAndView postChangePassword(@RequestParam Map<String, String> body) {
        Boolean success = userService.changePassword(body.get("email"), body.get("password"),
                body.get("matchesPassword"));
        if (!success) {
            ModelAndView mav = new ModelAndView("changePassword");
            mav.addObject("email", body.get("email"));
            mav.addObject("passwordsNotMatch", true);

            return mav;
        }

        return new ModelAndView("login");
    }

还是带有try-catch块?

0 个答案:

没有答案