20

I am using HandlerInterceptor in Spring Boot for processing common types of requests. But while executing preHandle, I want to return error status code to user if conditions are not met. If i throw the exception inside preHandle the response will have all the exception stack. How to send custom body as response with response code from preHandle

1
  • By calling the appropriate methods on the response parameter object. Which part of that would not be clear from the definition of the preHandle() method? Commented Sep 18, 2016 at 7:15

1 Answer 1

38

If conditions are not met, you can use response.setStatus(someErrorCode) to set the response status code and return false to stop execution. To send custom body you can use the following method: response.getWriter().write("something");

Here is the full example.

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

    if (conditionsNotMet()) {
        response.getWriter().write("something");
        response.setStatus(someErrorCode);

        return false;
    }

    return true;
} 

Hope this helps.

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

7 Comments

still the body is not visible , i am only seeing statuscode. Am i doing anything wrong
What do you mean body is not visible?
I mean i didnt get anything in response except status as errorcode that is send
When you use this method response.getWriter().write("something");, you'll get "something" message in the response body
i am getting default msg "error" instead of "something"(custom exception msg). Any help would be appreciated.
|

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.