javaliferayliferay-hook

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


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.


Solution

  • 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