Java 从异常处理程序返回响应实体[Spring]
我使用下面的代码来处理用Java 从异常处理程序返回响应实体[Spring],java,spring,Java,Spring,我使用下面的代码来处理用@ControllerAdvice @ExceptionHandler(RuntimeException.class) public ResponseEntity<JSONObject> RuntimeExceptionHandler(RuntimeException e) throws JSONException { JSONObject response = new JSONObject(); response.put("message",
@ControllerAdvice
@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);
}
这不是我所期望的。状态代码不是BAD_REQUEST
,json与response
不同
如果我将JSONObject
更改为String
,并传入一个字符串消息而不是一个json对象,则效果很好。我还在return
语句前面加了一个断点,因此响应看起来很好
注意:还有一篇帖子:
没有公认的答案
正在用@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);
}
@ExceptionHandler(RuntimeException.class)
公共响应属性RuntimeExceptionHandler(RuntimeException e){
JSONObject响应=新建JSONObject();
response.put(“message”,即getMessage());
返回新的ResponseEntity(response.toString(),HttpStatus.BAD_请求);
}
你的问题是什么?嗯,答案不是应该的。
@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);
}