I am trying to forward my request to error page when error occurs during generating excel sheet. Here is sample code below. I am not sure why it is not getting forwarded to error page when the exception is thrown, it is displaying blank page but not going to my error page for sure.`
@ResourceMapping("xyz")
public void generateExcelExport(ResourceRequest request, ResourceResponse response) {
try {
//Do all the excel related logic
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setProperty("Content-Disposition", "attachment; filename=\"" + XYZ + "\"");
workbook.write(response.getPortletOutputStream());
} catch (Exception e) {
response.setProperty("Content-Disposition", "inline" );
response.setContentType("text/html");
PortletRequestDispatcher dispatcher = request.getPortletSession().getPortletContext().getRequestDispatcher("/WEB-INF/views/html/jsp/error.jsp");
try {
dispatcher.forward(request, response);
} catch (Exception e1) {
log.error("Unable to forward the request from the portlet", e1);
}
} }
Im not sure but my guess would be that you didnt set any render parameter when redirecting to your error page.
Try this and see if it helps in any way (you can place it instead of the line with dispatcher):
response.setRenderParameter("jspPage", "/WEB-INF/views/html/jsp/error.jsp");
I am using this kind of redirects with actionResponse but it should work with resourceResponse as well...
EDIT: resource response does not contain setRenderParameter method, but zou can try to use the following approach:
create renderURL using response.createRenderURL()
. If a request is triggered using this URL, it will result in render request/response (or action request which can access that method).
The problem is, that you are trying to redirect to another page during resource phase of the portlet (render phase in not called during this phase).
I'm not 100% sure this would work in the resourcePhase, but you could try
com.liferay.portal.kernel.servlet.SessionErrors.add(request, "your Error message here");
I had a similar issue. This works -
PortletURL renderUrl = resourceResponse.createRenderURL();
renderUrl.setParameter("renderException", ex.toString());
resourceResponse.addProperty("Location", renderUrl.toString());
Maybe it is not forwarding because the response has already been committed because you have written something in it. That could explain why include works and forward doesn't.
You can check whether the response has already been committed using resourceResponse.isCommitted() in your catch block.