2

In my MVC controller I have a handler method with a signature:

public void myAction(ActionRequest request, ActionResponse response, Model model) {...}

And in this method I check if some submitted data is okay. If it's not valid, I want to set an error. Currently I do it this simple way:

model.addAttribute("operationStatus", "error");
model.addAttribute("operationMessage", "a lot of things went wrong");

and in the view JSP:

<c:if test="${requestScope.operationStatus == 'error'}">
    <div class="msg-error">${requestScope.operationMessage}</div>
</c:if>

Surely there has to be a better way to handle errors in Spring Portlet MVC. Note that I need to display the error messages in different places, not only in <form> tag.

So how should I handle errors?

Queequeg
  • 2,824
  • 8
  • 39
  • 66

1 Answers1

3

If you're targeting just Liferay, then you can use the SessionErrors class so you can do the following:

SessionErrors.add(actionRequest, "some-error");

Then on your JSP you have:

<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<liferay-ui:error key="some-error" message="Your error message goes here!" />

You can also use do this with exceptions. Check out my answer here.

Community
  • 1
  • 1
Jonny
  • 2,663
  • 1
  • 24
  • 24
  • Seems nice. But then I have to list a bunch of `` tags one after another i.e. when I have 20 possible errors I will have to list 20 jsp tags in my view? – Queequeg Jul 17 '12 at 05:47
  • Yup! I'm afraid that is true, and there isn't away around it (as far I'm aware) using Liferay tags. The only other way would be write some code to go through Session Errors and output the errors, but to be honest the above is the best way. – Jonny Jul 17 '12 at 07:35
  • I've just checked, that `SessionErrors` has an overload that takes 3 arguments - the 3rd is `value`. What is this? – Queequeg Jul 23 '12 at 08:09
  • Looking at the Liferay source code I would guess at that the value parameter is a way of specifying an error message. The normal behaviour is using the key to do a lookup in a properties file to get the appropriate message. Value probably overrides this message. – Jonny Jul 23 '12 at 08:36