12

I am new to this @ExceptionHandler. I need to return response in JSON format if there is any exception. My code is returning response in JSON format if the operation is successful. But when any exception is thrown it is return HTML response as I have used @ExceptionHandler.

Value and reason in @ResponseStatus is coming properly but in HTML. How can I can change it to a JSON response? Please help.

In my controller class i have this methods:

@RequestMapping(value = "/savePoints", method = RequestMethod.POST, consumes = "application/json", produces = "application/json;charset=UTF-8")
public @ResponseBody
GenericResponseVO<TestResponseVO> saveScore(
        @RequestBody(required = true) GenericRequestVO<TestVO> testVO) {
    UserContext userCtx = new UserContext();
    userCtx.setAppId("appId");
    return gameHandler.handle(userCtx, testVO);
}

Exception handling method:

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Error in the process")
@ExceptionHandler(Exception.class)
public void handleAllOtherException() {

}

2 Answers 2

13

You can annotate the handler method with @ResponseBody and return any object you want and it should be serialized to JSON (depending on your configuration of course). For instance:

public class Error {
    private String message;
    // Constructors, getters, setters, other properties ...
}

@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public Error handleValidationException(MethodArgumentNotValidException e) {
    // Optionally do additional things with the exception, for example map
    // individual field errors (from e.getBindingResult()) to the Error object
    return new Error("Invalid data");
}

which should produce response with HTTP 400 code and following body:

{
    "message": "Invalid data"
}

Also see Spring JavaDoc for @ExceptionHandler which lists possible return types, one of which is:

@ResponseBody annotated methods (Servlet-only) to set the response content. The return value will be converted to the response stream using message converters.

Sign up to request clarification or add additional context in comments.

4 Comments

What if I want to have a JSON body, and control over the status code?
Never mind that. What if Spring decides not to convert to JSON at all? How do I find out why?
itll go to that method but wont return that response. returns stacktrack in json
How to implement it in the Rest controller? And what is in MethodArgumentNotValidException.class? Can you write examples?
8

Replace

@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "Error in the process")

by

@ResponseStatus(value = HttpStatus.NOT_FOUND)

the 'reason' attribute force html render! I've waste 1 day on that.....

1 Comment

This is what, I was looking for. Saved my day

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.