1

I am trying to put interceptor to handle my custom authentication logic. So my prehandler will throw an exception if person in not logged in . I have my ErrorHandler controller added in script[/error] which gives json formatted error.

But when prehandler throws an exception it's all in html format, can i redirect my request to /error controller or if possible give my response in json format.

Script

public class AuthenticationInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler) throws Exception {

    throw new Exception("HELLO");
}

}

Current Output

<title>Apache Tomcat/8.5.11 - Error report</title>

HTTP Status 500 - Request processing failed; nested exception is java.lang.Exception: HELLO

Error

Expected Output

{"timestamp":1496584878547,"status":500,"error":"Found","message":"Hello"}
1
  • Did you find any solution by yourself already? I have the same issue. Commented Sep 19, 2018 at 14:34

1 Answer 1

0

As per this discussion we cannot directly use controller advice with handlers. Here is how i have achieved it.

  • Create json string for error message
  • Use HttpServletResponse to write this error message to downstream

Ex.

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        final String tenantId = request.getHeader(X_TENANT_ID);
        if (ObjectUtils.isEmpty(tenantId)) {
            return returnErrorResponse(response);
        } else {
            Assert.notNull(tenantId, tenantExceptionMessage);
            TenantIdContext.setTenantIdContext(tenantId);
            return true;
        }
    }

Error message implementation

private boolean returnErrorResponse(HttpServletResponse response) throws IOException {
        final int httpErrorCode = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(httpErrorCode);
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        final String jsonMessage = objectMapper.writeValueAsString(new TenantIdMissing(tenantExceptionMessage.get(), httpErrorCode));
        System.out.println(jsonMessage);
        response.getWriter().write(jsonMessage);
        return false;
    }

Object mapper as instance variable for lazy devs to create json string.

private final ObjectMapper objectMapper = new ObjectMapper();

Another good reference

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.