我在 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,未设置内容类型。 有什么建议吗?
最佳答案
你可以这样尝试吗?这是一个代码片段,请根据要求进行修改。
@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);
}
}
关于java - Spring ExceptionHandler 未返回有效的响应代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56480997/