I am handling my response model by RestControllerAdvice. And I am trying to use @ExceptionHandler to handle errors.
@RestControllerAdvice("cn.songxh.demo.web")
public class MyResponseBodyAdvice implements ResponseBodyAdvice {
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
MyResponse resp = new MyResponse();
resp.setData(body);
return resp;
}
@ExceptionHandler(Exception.class)
public MyResponse exceptionHandler(Exception e) {
e.printStackTrace();
MyResponse resp = new MyResponse();
resp.setSuccess(false);
return resp;
}
}
I would like it return {"success":false}
to client.
Unfortunately, I get {"success":true}{"success":false}
when HttpMessageNotWritableException
occurs. It is even not an valid json string.
I create a demo project in https://github.com/tsingheng/exception-handler-demo.