lundi 6 avril 2015

Spring handling exceptions (execute every statement)

I want some cleaner error handling, if Spring offers that. i've got the following class:



public class A{
private int a;
private int b;

public void setA(int a){
if(a==0){throw new IllegalArgumentException("a cannot be 0");}
this.a=a;

}

public void setB(int b){
if(b>5){throw new IllegalArgumentException("B must be greater than 5");}
this.b=b;
}

}


Inside my controller in Spring I create an A object, from input a user gave me via a form



public String addA(@RequestParam(value="a") String a,@RequestParam(value="b") String b){

A a=new A();

a.setA(a); // <- first error might be triggered
a.setB(b); // <- second error might be triggered

//The following code may only be executed when there are no errors:
service.addA(a);
return "redirect:/Overview.page";
}


Without Spring, I would just create an error arrayList and put the setA and setB in a seperate try/catch block and populate the error arrayList And then I would check if the errorList is empty, so I know if I can add 'a' to the service.


I was wondering if there is a cleaner way in Spring to do this error handling. My entire model is already equiped with 'Throw Exceptions', so using the annotation, is not an option I guess.


So how do I handle these errors in Spring? I don't want the code to stop if one error is triggered. For example if the user fills in a=0 and b=3. I want both error messages on my form.


Thanks in advance


Aucun commentaire:

Enregistrer un commentaire