繁体   English   中英

从异常处理程序返回响应实体[Spring]

[英]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看起来很好。

注意 :有是另一篇文章在这里它:

  1. 没有接受的答案。
  2. @ResponseBody注释方法我没有。
  3. 不使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM