【问题标题】:Returning response entity from an Exception handler [Spring]从异常处理程序返回响应实体 [Spring]
【发布时间】:2017-06-02 04:26:40
【问题描述】:

我使用下面的代码来处理类中所有RuntimeException类型的异常@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);
}

如果是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 看起来不错。

注意:还有一个帖子here

  1. 没有接受的答案。
  2. 我没有用@ResponseBody 注释方法。
  3. 没有使用JSONObject

【问题讨论】:

  • 你有什么问题?
  • 嗯,反应不是应该的。

标签: java spring


【解决方案1】:

如果您需要返回 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);
 }

【讨论】:

    猜你喜欢
    • 2016-05-24
    • 2022-07-29
    • 2019-08-29
    • 1970-01-01
    • 2013-08-13
    • 2018-05-20
    • 2015-07-26
    • 2015-09-03
    • 1970-01-01
    相关资源
    最近更新 更多