httperror-handlingaemsling

How to bypass AEM default error handling?


Is it possible to directly return a HTTP error response with custom contents from a Sling servlet running in AEM?

Background

There is a Sling servlet that processes forms sent with the POST method.

@SlingServlet(
    methods = HttpConstants.METHOD_POST,
    resourceTypes = NameConstants.NT_PAGE,
    selectors = SELECTOR)
public class MyServlet extends SlingAllMethodsServlet {
//...
    @Override
    protected void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) {
        //if something is wrong with the request
        Gson gson = new Gson();
        gson.toJson(errorResponse, response.getWriter());
        response.setContentType(MediaType.JSON_UTF_8.toString());
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        //...
    }
//...
}

When it returns HTTP 400 Bad Request, I'd like to get the JSON response created in the servlet. Instead, AEM returns a HTML page, generated with /apps/sling/servlet/errorhandler, only with the JSON added at the beginning of the content.

{"errors":["The provided value is incorrect"]}



<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html>
    <head><title>400 Bad Request</title></head>
    <body> 
                    <h1>400 Bad Request</h1>
                    <p>Cannot serve request to on this server.</p>
(...)
    </body>
</html>

I am aware that it is possible to create custom error pages. The problem is that I need validation errors from the servlet to create a meaningful error response.

AEM version: 6.5


Solution

  • Just use response.setStatus(...), instead of response.sendError(...).

    So just call:

    response.setStatus(HttpServletResponse.SC_BAD_REQUEST);