Petar Petrov
Petar Petrov

Reputation: 596

Spring MVC How to log all the errors from BindingResult

I have a controller which makes post method. The controller's method validates a entity. In case some errors occurred it redirects to error page otherwise it saves the entity. My code looks like that:

public String createEntity(Entity entity, BindingResult result) {
   // Validate here
   if(result.hasErrors) {
     return "errorPage";
   }

   service.create(entity);
   return "some view";
}

So now if there are errors I want to log them all. I've read this article

How to get error text in controller from BindingResult

but I don't want to type check.

Is there a clever way to do that?

Thank you.

Upvotes: 2

Views: 2382

Answers (1)

Mohamed Nabli
Mohamed Nabli

Reputation: 1649

it is very simple just add error list to your model

public String createEntity(Entity entity, BindingResult result,Model model) {
   // Validate here
   if(result.hasErrors) {
     model.addAttribute("errors",result.getAllErrors());
     return "errorPage";
   }else {
      service.create(entity);
      return "some view";
   }
}

later in your jsp :

<c:if test="${not empty errors}">
//foreach element show error (just an exampl)
</c:if>

Upvotes: 2

Related Questions