自定义异常

Custom Exceptions

我正在尝试定义我自己的自定义异常。基本上,如果年龄小于 16 岁,我想阻止创建用户。在一些讨论/问题之后,我到目前为止已经想出了这个。

public enum Code {

    USER_INVALID_AGE("The user age is invalid");

    private String message;

    Code(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

}

异常class:

public class TrainingException extends RuntimeException {

private Code code;

    public TrainingException(Code code) {
        this.code = code;
    }

    public Code getCode() {
        return code;
    }

    public void setCode(Code code) {
        this.code = code;
    }
}

在验证程序包中,我有以下内容:

public class UserValidator implements Validator<User> {

    /** {@inheritDoc} */
    @Override
    public void validate(User type) {
        if (DateUtils.getYearDifference(type.getUserDetails().getBirthDate(), new DateTime())< 16) {
            throw new TrainingException(Code.USER_INVALID_AGE);
        }
    }
}

我在服务中调用验证方法,我尝试在其中创建用户:

public User save(User user) {
        validator.validate(user);
        return userRepository.save(user);
    }

这就是我目前所拥有的,我尝试对此进行测试但没有成功。

@ Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testInvalidAge() throws TrainingException{

        thrown.expect(TrainingException.class);
        thrown.expectMessage(Code.USER_INVALID_AGE.getMessage());

        User user = userService.findAll().get(0);
        UserDetails userDetails = new UserDetails();
        userDetails.setBirthDate(UserTestUtils.buildDate(2000, 7, 21, 1, 1, 1));
        user.setUserDetails(userDetails);

        userService.save(user);
    }

这是我得到的:

Expected: (an instance of org.dnet.training.exceptions.TrainingException and exception with message a string containing "The user age is invalid") but: exception with message a string containing "The user age is invalid" message was null.

很明显我遗漏了一些东西但我卡住了,尝试了不同的东西但到目前为止没有任何成功。

您通过 throw new TrainingException(Code.USER_INVALID_AGE); 创建了一个未设置消息的异常。在 TrainingException 的构造函数中调用 super(code.getMessage()); 将为该异常实例设置消息。

尝试像下面这样重写您的自定义异常,希望对您有所帮助:)

public class TrainingException extends RuntimeException {

    private Code code;

    public TrainingException(Code code) {
        super(code.getgetMessage());
        this.code = code;
    }

    public Code getCode() {
        return code;
    }

    public void setCode(Code code) {
        this.code = code;
    }
}

在 TrainingException 构造函数中首先调用 super(code.name()) 然后调用 this.code = 代码即

public TrainingException(Code code) {super(code.name()) this.code = code;}

它会起作用。