Display custom error message from a liferay hook service after an exception

2.3k views Asked by At

I am overriding the addArticle and updateArticle methods of JournalArticleServiceImpl using a Hook. I am checking for all articles with a particular ddmStructureKey and that the current article has a unique value in a particular field.

I am throwing DuplicateEntryException exception when I find non-uniqueness. Within the curresponding catch method, I gave return null;. But it threw a NullPointerException. Then I tried to throw SystemException like follows.

try {
// logic
} catch (DuplicateEntryException e) {
    LOG.error("Value already present", e);
    throw new SystemException("Value already present", e);
}

But the result for the end users was as shown below. Even though in the logs, it displayed the actual error, it is not possible for users to understand what exactly happened in the background from this message.

enter image description here

I do not know how to display a custom error message to the end users from a Hook. Also to return to the same page to edit the same article.

2

There are 2 answers

4
Peter B On BEST ANSWER

Display error messages in Liferay:

You may use session messages, like <liferay-ui:error> tag.

For example in the jsp page:

<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
...
<liferay-ui:error key="err1" message="Third message" translateMessage="false"/>

or with exception, like in edit_article.jsp:

<liferay-ui:error exception="<%= ArticleContentSizeException.class %>" message="you-have-exceeded-the-maximum-web-content-size-allowed" />

You can define your own exception class and your own message-key and the value for the key in Language.properties.

And in the render method:

SessionErrors.add(renderRequest, "err1");

or when catching an exception (e) use this:

SessionErrors.add(renderRequest, e.getClass());

A complete example on github - portlet, github - hook

2
Olaf Kock On

As the UI layer seems to not expect any exception from these methods, this might call for changes in the UI- or Action-layer as well. When you do that, you might even get well along without service changes (because you can check upfront).

A hacky idea might be to not return null, but the duplicated value - simulating a successful update but returning the already existing article. Note that this is hacky, I'm not sure if it works always. If it breaks, please let me know how it breaks.