Reputation: 597
I currently have a Spring MVC servlet that process a file that is uploaded via the initial form page.
The request handler already does some validation on the file if it's missing certain requirements, but unfortunately it's unable to easily tell if all the requirements are met until the processing actually occurs.
@RequestMapping(path = "/", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String submit(@Valid FormData form, BindingResult result, Model model) throws IOException, ParseException
{
if (result.hasErrors())
{
return "index";
}
processFile(form.getFile());
return "success";
}
If an exception occurs at the processing step, I handle it in an @ExceptionHandler
annotated method. However, this method requires having a second line for showing the error in the JSP page:
<form:input type="file" name="file" path="file" value=""/>
<form:errors path="file" element="label" class="error" for="file"/>
<c:if test="${not empty error}"><label class="error">${error}</label></c:if>
with the method itself looking like
@ExceptionHandler(Exception.class)
public String databaseError(Model model, Exception e)
{
model.addAttribute("formData", new FormData());
model.addAttribute("error", "File failed to process. Please verify the contents of the file.");
return "index";
}
Is there a way to leverage BindingResult
to handle an exception as a validation error to avoid the redundant error message templating?
Upvotes: 3
Views: 671
Reputation: 48616
You can catch the exception inside your request handling method, and then manipulate the BindingResult in your catch clause.
Upvotes: 1