我使用以下代码来处理在@ControllerAdvice注释的类中RuntimeException类型的所有异常
@ExceptionHandler(RuntimeException.class)
public ResponseEntity RuntimeExceptionHandler(RuntimeException e) throws JSONException {
JSONObject response = new JSONObject();
response.put("message", e.getMessage());
return new ResponseEntity(response, HttpStatus.BAD_REQUEST);
}
如果发生ValidationException,它将重新响应以下响应给客户端:
{
"timestamp": 1496377230943,
"status": 500,
"error": "Internal Server Error",
"exception": "javax.validation.ValidationException",
"message": "Name does not meet expectations",
"path": "/signup"
}
这不是我所期望的.状态代码不是BAD_REQUEST,并且json与响应不同.
如果我将JSONObject更改为String并传递字符串消息而不是json对象,则效果很好.我还在return语句之前放置了一个断点,并且响应看起来还不错.
注意:还有另一篇文章here,其中:
>没有可接受的答案.
>使用@ResponseBody注释了我没有的方法.
>不使用JSONObject
解决方法:
如果需要返回的JSON格式,则可以快速解决:
@ExceptionHandler(RuntimeException.class)
public ResponseEntity RuntimeExceptionHandler(RuntimeException e) {
JSONObject response = new JSONObject();
response.put("message", e.getMessage());
return new ResponseEntity(response.toString(), HttpStatus.BAD_REQUEST);
}
标签:spring,java
来源: https://codeday.me/bug/20191111/2018959.html