Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

springboot : how to return error status code in prehandle of HandlerInterceptor

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

like image 513
santosh kumar Avatar asked Sep 18 '16 06:09

santosh kumar


1 Answers

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.

like image 95
Arsen Davtyan Avatar answered Oct 17 '22 10:10

Arsen Davtyan