Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get response in JSON format using @ExceptionHandler in Spring MVC

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() {

}
like image 218
soumitra chatterjee Avatar asked Sep 30 '15 15:09

soumitra chatterjee


People also ask

What is the difference between ControllerAdvice and RestControllerAdvice?

The differences between @RestControllerAdvice and @ControllerAdvice is : @RestControllerAdvice = @ControllerAdvice + @ResponseBody . - we can use in REST web services. @ControllerAdvice - We can use in both MVC and Rest web services, need to provide the ResponseBody if we use this in Rest web services.

How do you handle authentication and exception handling in Spring Boot and Spring MVC applications?

Spring MVC provides exception handling for your web application to make sure you are sending your own exception page instead of the server-generated exception to the user. The @ExceptionHandler annotation is used to detect certain runtime exceptions and send responses according to the exception.

What is true about the @ExceptionHandler and @ControllerAdvice annotations?

Exception Handler with Controller Advice in Spring The @ExceptionHandler annotation indicates which type of Exception we want to handle. The exception instance and the request will be injected via method arguments. By using two annotations together, we can: control the body of the response along with status code.


2 Answers

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.

like image 200
Bohuslav Burghardt Avatar answered Nov 11 '22 02:11

Bohuslav Burghardt


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.....

like image 25
C2dric Avatar answered Nov 11 '22 02:11

C2dric