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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With