3

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?

1
  • I have same problem, have you found any solution for it? Commented May 31, 2018 at 5:32

1 Answer 1

1

You can catch the exception inside your request handling method, and then manipulate the BindingResult in your catch clause.

Sign up to request clarification or add additional context in comments.

1 Comment

You know, I just completely dismissed that idea from my thoughts. Is there anything I should worry about when catching a DataAccessException? I remember reading somewhere that it's something you shouldn't be catching, which is why I just didn't think about it before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.