Spring MVC Error Handling
This is not a tutorial of any sort. I’m adding this post to record the error-handling techniques of Spring MVC.
Catching
Errors can be caught in two places:
- Inside a validator (extended from Validator)
- Inside a controller
1. Validator
In the validate() overridden method, we can use two approaches:
a) Using the errors object:
errors.rejectValue(field, code, defaultMessage) → for field errors
errors.reject(code, defaultMessage) → for global/general errors
b) Using ValidationUtils.rejectXxx(…) methods
2. Controller
In the onSubmit(request, response, command, BindException errors) overridden method:
errors.rejectValue(field, code, defaultMessage) → for field errors
errors.reject(code, defaultMessage) → for global/general errors
…
return new ModelAndView(getFormView(), errors.getModel())
getFormView() returns us to the input form. The call to errors.getModel() is crucial here.
Reporting with JSP
<form:form command=”commandNameIfChangeFromDefault”>
<span class=”…”>
<spring:hasBindErrors name=”command”>
<c:forEach items=”${errors.allErrors} var=”error”> <!– or errors.globalErrors or errors.fieldErrors –>
<spring:message code=”${error.code}” text=”${error.defaultMessage}”/>
</c:forEach>
</spring:hasBindErrors>
</span>
</form:form>