PDA

View Full Version : Displaying Exception Errors With Binding


justin_dag
Apr 22nd, 2007, 11:07 AM
Greetings,

Scenario:
Do a form post, which is handled by a SimpleFormController. The onSubmit delgates its work to a service layer. Now let's say an exception is raised from the DAO layer.. perhaps a unique constraint is violated...

Question:
How would I display that exception error message in my UI, via form binding. (<c:out value="${status.errorMessage}"/>) ?

If this can't be done via binding, can you think of alternative?

Thanks in advance.

---
Justin

cwilkes
Apr 22nd, 2007, 11:42 AM
Do you know what unique constraint was violated? If not you might want to write a query to find out if the username was taken, etc. Then base your errors on that field.

Thinking along those lines you could put in a validator a check that looks for the same known unique constraint and then report an error there before even trying to update the database. That makes your controller know a little about your database model, but shouldn't be that big of a deal.

Axrunz
Apr 22nd, 2007, 12:07 PM
justin,
You have mentioned form-binding ...it seems you are using struts.
In your case, you can define your own custom exception class and in case of any exception in DAO, create an object of custom exception with appropriate message in it and pass it on to action class where, create an action error which can be displayed in UI with <html:error> tag.

But, better way will be use of struts-tag lib..basically ,<bean:message> tag

justin_dag
Apr 22nd, 2007, 10:50 PM
Thanks for the replies.

Axrunz -- I am using straight up Spring MVC. When I say "binding", I'm talking about using the spring tags:
<s:bind path="command.id">

cwilkes -- I've just moved this unique check to a validator, but I'm not too wild about pulling it out of my service layer. If this service is used by another client (not spring), the validation will not be there.

I'd still like to know how to tap into the binding stuff...that way I can pass the exception to org.springframework.validation.Errors, and then bind it to the form, like a Validator does.

justin_dag
Apr 25th, 2007, 08:01 PM
I think this is what I was looking for..

try {
User user = myService.authenticate(username, password);
}
catch (DataIntegrityViolationException ex) {
errors.rejectValue("account.username", "USER_ID_ALREADY_EXISTS",
"User ID already exists: choose a different ID.");
return showForm(request, response, errors);
}

I haven't tried it, but it seems like it will work.


---
Justin