rest - Spring @ExceptionHandler does not work with @ResponseBody -
i try configure spring exception handler rest controller able render map both xml , json based on incoming accept header. throws 500 servlet exception right now.
this works, picks home.jsp:
@exceptionhandler(illegalargumentexception.class) public string handleexception(final exception e, final httpservletrequest request, writer writer) { return "home"; }
this not work:
@exceptionhandler(illegalargumentexception.class) public @responsebody map<string, object> handleexception(final exception e, final httpservletrequest request, writer writer) { final map<string, object> map = new hashmap<string, object>(); map.put("errorcode", 1234); map.put("errormessage", "some error message"); return map; }
in same controller mapping response xml or json via respective converter works:
@requestmapping(method = requestmethod.get, value = "/book/{id}", headers = "accept=application/json,application/xml") public @responsebody book getbook(@pathvariable final string id) { logger.warn("id=" + id); return new book("12345", new date(), "sven haiges"); }
anyone?
your method
@exceptionhandler(illegalargumentexception.class) public @responsebody map<string, object> handleexception(final exception e, final httpservletrequest request, writer writer)
does not work because has wrong return type. @exceptionhandler methods have 2 valid return types:
- string
- modelandview.
see http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html more information. here's specific text link:
the return type can string, interpreted view name or modelandview object.
in response comment
thanx, seems overread this. that's bad... ideas how provides exceptions automatically in xml/json format? – sven haiges 7 hours ago
here's i've done (i've done in scala i'm not sure if syntax correct, should gist).
@exceptionhandler(throwable.class) @responsebody public void handleexception(final exception e, final httpservletrequest request, writer writer) { writer.write(string.format( "{\"error\":{\"java.class\":\"%s\", \"message\":\"%s\"}}", e.getclass(), e.getmessage())); }
Comments
Post a Comment