Spring 为什么@RestControllerAdvice类上的方法返回HTML而不是JSON?

Spring 为什么@RestControllerAdvice类上的方法返回HTML而不是JSON?,spring,Spring,我有以下异常处理程序: @RestControllerAdvice @RequiredArgsConstructor public class ControllerExceptionHandler { @ExceptionHandler(FeignException.class) @ResponseBody public String afterThrowing(FeignException ex, HttpServletResponse response) {

我有以下异常处理程序:

@RestControllerAdvice
@RequiredArgsConstructor
public class ControllerExceptionHandler {

    @ExceptionHandler(FeignException.class)
    @ResponseBody
    public String afterThrowing(FeignException ex, HttpServletResponse response) {
        response.setStatus(ex.status());
        return ex.contentUTF8();
    }

}
我希望当伪异常传播到我的一个REST控制器时

将调用后hrowing方法 返回给HTTP客户机的响应将是JSON
方法被调用,但返回给客户端的内容类型是HTML而不是JSON。如何返回JSON而不是HTML?

您应该使用somethingclass或map来包装您的响应

包装类:

public class ApiError {
    private HttpStatus status;
    private String response;

    public ApiError(String response, HttpStatus status) { 
       this.response = s;
       this.status = status;
    }

    // getter setter
} 
和异常处理程序:

  @ExceptionHandler(FeignException.class)
  protected ResponseEntity<Object> handleFeignException(FeignException ex) {
    ApiError apiError = new ApiError(ex.contentUTF8(), NOT_ACCEPTABLE);
    return new ResponseEntity<>(apiError, apiError.getStatus());
  }
要进一步阅读,您可以检查以下问题:

编辑: 由于ex.contentUTF8调用返回有效的JSON,因此不需要包装它。只需返回带有ResponseEntity的字符串

  @ExceptionHandler(FeignException.class)
  protected ResponseEntity<String> handleFeignException(FeignException ex) {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<>(ex.contentUTF8(), headers, BAD_REQUEST);
  }

谢谢你的回答。我需要对JSON的响应如下[{type:ERROR,message:blah}]。ex.contentUTF8将其作为字符串返回。我不想以{status:…,response:[{type:ERROR,message:blah}]}的形式返回JSON,这就是您的解决方案将返回的内容。这太好了。谢谢在我的情况下,我还希望将原始状态提供给客户机。所以,我将return语句改为返回新的ResponseEntityex.contentUTF8,headers,HttpStatus.valueOfex.status;