可以为业务验证抛出异常吗?

时间:2019-06-07 23:10:05

标签: validation jsf exception java-ee business-logic

我正在使用JSF,Bean验证,EJB等开发Java EE应用程序。我试图找到进行业务验证的正确方法。

我将bean验证用于基本方案(@NotNull@Size等),但是对于复杂的业务验证,我决定采用策略模式(尝试了级别类验证,太冗长)。实现如下:

public void signUp(Company company, UserAccount userAccount) throws ValidationException {
    //Set the validations to be executed
    List<Validator> validatorsList = new ArrayList<>();
    validatorsList.add(new Validator1(company));
    validatorsList.add(new Validator2(userAccount, ejb2));

    //Execute the validations
    for (Validator validator : validatorsList) {
    if (!validator.validate()) {
        validator.throwException();
    }

    //Execute some logic
}

以上代码在EJB(Ejb1)中运行

界面:

public interface Validator {

    public boolean validate();

    public void throwException() throws ValidationException;

}

验证者:

public class Validator1 implements Validator {

    private Company company;

    public Validator1 (Company company) {
        this.company = company;
    }

    @Override
    public boolean validate() {
        return doSomething();
    }

    @Override
    public void throwException() throws ValidationException {
        throw new ValidationException2();
    }
}

public class Validator2 implements Validator {

    private Ejb1 ejb2;
    private Company company;

    public Validator2 (Company company, Ejb2 ejb2) {
        this.company = company;
        this.ejb2= ejb2;
    }

    @Override
    public boolean validate() {
        return ejb2.doSomething();
    }

    @Override
    public void throwException() throws ValidationException {
        throw new ValidationException2();
    }
}

抽象异常

public abstract class ValidationException extends Exception {

    private static final long serialVersionUID = 1L;

}

具体异常

@ApplicationException(rollback = true)
public static class ValidationException1 extends ValidationException 
    implements Serializable {

    private static final long serialVersionUID = 1L;

}

@ApplicationException(rollback = true)
public static class ValidationException2 extends ValidationException  
    implements Serializable {

    private static final long serialVersionUID = 1L;

}

JSF托管bean:

public String save() {
    try {
        this.ejb.signUp(this.company, this.user);
    }
    catch (ValidationException1 e) {
        //Show info message
    }
    catch (ValidationException2 e) {
        //Show info message
    }
    catch (Exception e) {
        //Show error message
    }

    return null;
}

上面的代码很好用,但是我有以下问题:

  • 这是一个正统的解决方案吗?
  • 是否可以将EJB传递给验证类的构造函数?如果没有,正确的方法是什么?
  • 返回某种错误列表而不是引发异常会更好吗?

谢谢

0 个答案:

没有答案