简体   繁体   中英

Returning response entity from an Exception handler [Spring]

I use the following code to handle all exceptions of type RuntimeException in class annotated with @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);
}

It retuns the following response to the client in case of a ValidationException :

{
  "timestamp": 1496377230943,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "javax.validation.ValidationException",
  "message": "Name does not meet expectations",
  "path": "/signup"
}

It is not what I expected. The status code is not BAD_REQUEST and the json is different from response .

It works fine if I change JSONObject to String and pass in a string message instead of a json object. I also put a break point before return statement and the response looks fine.

Note : There is another post here which:

  1. Has no accepted answer.
  2. Is annotating the method with @ResponseBody which I didn't.
  3. Is not using JSONObject

A quick fix if you require a returned JSON format:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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