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 Answer
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.
7 Comments
santosh kumar
still the body is not visible , i am only seeing statuscode. Am i doing anything wrong
Arsen Davtyan
What do you mean body is not visible?
santosh kumar
I mean i didnt get anything in response except status as errorcode that is send
Arsen Davtyan
When you use this method
response.getWriter().write("something");, you'll get "something" message in the response bodyRaja aar
i am getting default msg "error" instead of "something"(custom exception msg). Any help would be appreciated.
|
responseparameter object. Which part of that would not be clear from the definition of thepreHandle()method?