19

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

Ali Dehghani
  • 46,221
  • 15
  • 164
  • 151
santosh kumar
  • 1,465
  • 3
  • 13
  • 14
  • By calling the appropriate methods on the `response` parameter object. Which part of that would not be clear from the definition of the [`preHandle()`](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/HandlerInterceptor.html#preHandle-javax.servlet.http.HttpServletRequest-javax.servlet.http.HttpServletResponse-java.lang.Object-) method? – Andreas Sep 18 '16 at 07:15

1 Answers1

37

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.

Arsen Davtyan
  • 1,891
  • 8
  • 23
  • 40
  • still the body is not visible , i am only seeing statuscode. Am i doing anything wrong – santosh kumar Sep 18 '16 at 07:57
  • What do you mean body is not visible? – Arsen Davtyan Sep 19 '16 at 04:31
  • I mean i didnt get anything in response except status as errorcode that is send – santosh kumar Sep 19 '16 at 05:24
  • When you use this method `response.getWriter().write("something");`, you'll get "something" message in the response body – Arsen Davtyan Sep 19 '16 at 05:28
  • i am getting default msg "error" instead of "something"(custom exception msg). Any help would be appreciated. – Raja aar Feb 08 '21 at 12:27
  • Could someone elaborate on the `stop execution` part of this answer? Will it not go through any additional `HandlerInterceptor`'s if marked false? Will it not make it to the handler itself if marked false? – Copy and Paste Sep 30 '21 at 07:08
  • @CopyandPaste before getting to the actual controller, spring will call all the interceptors in the order you specified to it. If a preHandler interceptor returns false, it doesnt call anything else and return what you specified it to return via the HttpServletResponse object – motorola Jun 04 '22 at 02:56