[英]Spring ExceptionHandler does not return valid response code
I have such Exception handler in spring RestController. 我在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;
}
I expect result: Content-type: application-json Status: 403 And body: 我期望结果:内容类型:application-json状态:403和正文:
{"date":"06-06-2019 18:36:34","errorCode":"102","error":"Login or password is not right","message":"Access denied"}
But result is: Status: 200 and Content-type is not set. 但是结果是:状态:200,并且未设置Content-type。 Any suggestions?
有什么建议么?
Can you try like this. 你可以这样尝试吗 This is a code snippet, modify it as per the requirements.
这是一个代码段,请根据要求进行修改。
@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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.