0

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.

John
  • 365
  • 2
  • 5
  • 15
  • hey, you can follow my answer that Implemented about custom error handler https://stackoverflow.com/questions/58614373/how-to-convert-constraintviolationexception-500-error-to-400-bad-request/58614581#58614581 This works perfectly @John – Jonathan JOhx May 25 '21 at 13:40

1 Answers1

0

this might cause the result {"success":true}{"success":false}

 @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
       //this place add MyResponse -> {"success":true}
        MyResponse resp = new MyResponse();
        resp.setData(body);
        return resp;
    }

if you don't want to beforeBofyWrite do something
you don't need to implements ResponseBodyAdvice

link https://blog.csdn.net/u013887008/article/details/100183087

beichenhpy
  • 22
  • 2