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


i new @exceptionhandler. need return response in json format if there exception. code returning response in json format if operation successful. when exception thrown return html response have used @exceptionhandler.

value , reason in @responsestatus coming in html. how can can change json response? please help.

in controller class have 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 process") @exceptionhandler(exception.class) public void handleallotherexception() {  } 

you can annotate handler method @responsebody , return object want , should serialized json (depending on configuration of course). 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 additional things exception, example map     // individual field errors (from e.getbindingresult()) error object     return new error("invalid data"); } 

which should produce response http 400 code , following body:

{     "message": "invalid data" } 

also see spring javadoc @exceptionhandler lists possible return types, 1 of is:

@responsebody annotated methods (servlet-only) set response content. return value converted response stream using message converters.


Comments

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -