[英]Returning response entity from an Exception handler [Spring]
我使用以下代码来处理使用@ControllerAdvice
注释的类中的RuntimeException
类型的所有异常
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<JSONObject> RuntimeExceptionHandler(RuntimeException e) throws JSONException {
JSONObject response = new JSONObject();
response.put("message", e.getMessage());
return new ResponseEntity<JSONObject>(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与response
不同。
如果我将JSONObject
更改为String
并传入字符串消息而不是json对象,它可以正常工作。 我还在return
语句之前设置了一个断点, response
看起来很好。
注意 :有是另一篇文章在这里它:
@ResponseBody
注释方法我没有。 JSONObject
如果您需要返回的JSON格式,请快速修复:
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<String> RuntimeExceptionHandler(RuntimeException e) {
JSONObject response = new JSONObject();
response.put("message", e.getMessage());
return new ResponseEntity<String>(response.toString(), HttpStatus.BAD_REQUEST);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.