我在Spring RestController中有这样的异常处理程序。
@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;
}
我期望结果: 内容类型:application-json 状态:403 和身体:
{"date":"06-06-2019 18:36:34","errorCode":"102","error":"Login or password is not right","message":"Access denied"}
但是结果是: 状态:200,未设置内容类型。 有什么建议吗?
答案 0 :(得分:1)
您可以这样尝试吗?这是一个代码段,请根据要求进行修改。
@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);
}
}