开发者

Serialize exceptions to JSON with spring-mvc

@RequestMapping(..)
@ResponseBody
public SearchResponse search(SearchRequest request) throws SearchException { .. }

I want to return to the requester:

  • JSON-serialized search response in case everything is fine
  • JSON-serialized exception details if SearchException is t开发者_如何学JAVAhrown.

The first part works fine (having Jackson on the classpath and <mvc:annotation-driven />) but I don't see an easy way to serialize the exception as json.

I can register a custom handler, and write a JSON string from there, but I may also need XML serialization, which will mean I'll need conditionals in the handler. Isn't there something ready for that?


Here's what worked: I took axtavt's suggestion (annotating it with @Component), and added this method to the controller:

@ExceptionHandler(CustomException.class)
public @ResponseBody CustomException handleException(CustomException ex) {
    return ex;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜