Java Spring ExceptionHandler未返回有效的响应代码

Java Spring ExceptionHandler未返回有效的响应代码,java,spring,Java,Spring,我在SpringRestController中有这样的异常处理程序 @ExceptionHandler(AuthException.class) public ResponseEntity<String> handleCustomException(AuthException ex, Writer writer) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.setC

我在SpringRestController中有这样的异常处理程序

   @ExceptionHandler(AuthException.class)
public ResponseEntity<String> handleCustomException(AuthException ex, Writer writer) throws IOException {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    ResponseEntity responseEntity = new ResponseEntity(headers, HttpStatus.FORBIDDEN);
    (new ObjectMapper()).writeValue(writer, ex.getAsMap());

    return responseEntity;
}
但结果是: 状态:200,未设置内容类型。
有什么建议吗?

你能这样试试吗。这是一个代码片段,请根据需要进行修改

@ControllerAdvice
    public class GlobalExceptionHandler{
        @ExceptionHandler(MyCustomException.class)
        @ResponseBody
        public ResponseEntity<?> handleCustomException(MyCustomException e) {        
            String bodyJson = "Fatal Exception while performing.";
            return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON).body(bodyJson);
        }
    }
@ControllerAdvice
公共类GlobalExceptionHandler{
@ExceptionHandler(MyCustomException.class)
@应答器
公共响应handleCustomException(MyCustomException e){
String bodyJson=“执行时发生致命异常。”;
返回ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON).body(bodyJson);
}
}
@ControllerAdvice
    public class GlobalExceptionHandler{
        @ExceptionHandler(MyCustomException.class)
        @ResponseBody
        public ResponseEntity<?> handleCustomException(MyCustomException e) {        
            String bodyJson = "Fatal Exception while performing.";
            return ResponseEntity.status(HttpStatus.FORBIDDEN).contentType(MediaType.APPLICATION_JSON).body(bodyJson);
        }
    }