Message Boards
Status 404 from Try/Catch
Status 404 from Try/Catch
New Member Posts: 2 Join Date: 5/17/21 Recent PostsOne of our developers wrote a portlet that uses the
doView method to render relevant content. However, we
are receiving NPE's if the user goes to a page under a valid route of
that portlet with no valid record.
An example is:
/<location>/<postcode>/<propertyname>
/london/w1/10-downing-street -
VALID
/london/w1/sdsd-downing-streetsss - INVALID
The slug will pull the record from the db as it's unique but if
it's invalid it throws an NPE on
fillRenderRequestAttributes and we need it to throw a
status 404.
Code
public void doView(RenderRequest renderRequest, RenderResponse renderResponse) throws IOException, PortletException { fillRenderRequestAttributes(renderRequest, renderResponse); if(_log.isDebugEnabled()) { _log.debug("DoView"); } try { super.doView(renderRequest, renderResponse); } catch(Exception e) { _log.debug("Broken"); e.printStackTrace(); } }
I assume we need a try/catch around fillRenderRequestAttributes and in the catch we need to throw a 404? How can this be done? Any examples would be helpful.
RE: Status 404 from Try/Catch
New Member Posts: 2 Join Date: 5/17/21 Recent PostsThanks to Olaf Kock for the answer on StackOverflow:
doView
is rendering a portlet's output, not a
full page. Thus, it doesn't have a status code. The page is rendered
elsewhere (e.g. decorated with the theme, and with any number of other
portlets on the page that might still show relevant content).
In the portlet world you're not dealing
with HttpServletRequest
/Response
pairs, but
with PortletRequest
/Response
pairs (as seen
here in the incarnation
of RenderRequest
/Response
). Thinking in HTTP
return codes is wrong: You can't even guarantee that the portlet is
rendered before the response is already sent back to the browser: Once
you determine that your portlet can't render appropriate
output, the page might already be on its way, with status
code 200. Or it might be rendered asynchronously and just injected
into a page.
If the portlet can't render appropriate output
in doView
, you'll need to catch the exception and display
a proper error message in the portlet.
Otherwise, consider implementing serveResource
, where
you have more control, or a REST endpoint. But note: 404 is a
technical error, while you're handling a business layer error - both
should be handled differently.