Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从异常处理程序返回响应实体[Spring]_Java_Spring - Fatal编程技术网

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);
     }