×
文章路径: Java

SpringMVC HandlerExceptionResolver返回json数据

发表于5年前(May 26, 2017 9:21:00 PM)  阅读 9752  评论 2

分类: Java

标签: HandlerExceptionResolver springmvc resolveException json MappingJackson2JsonView

HandlerExceptionResolver是SpringMVC提供的全局异常处理接口。

public interface HandlerExceptionResolver {

	/**
	 * Try to resolve the given exception that got thrown during handler execution,
	 * returning a {@link ModelAndView} that represents a specific error page if appropriate.
	 * <p>The returned {@code ModelAndView} may be {@linkplain ModelAndView#isEmpty() empty}
	 * to indicate that the exception has been resolved successfully but that no view
	 * should be rendered, for instance by setting a status code.
	 * @param request current HTTP request
	 * @param response current HTTP response
	 * @param handler the executed handler, or {@code null} if none chosen at the
	 * time of the exception (for example, if multipart resolution failed)
	 * @param ex the exception that got thrown during handler execution
	 * @return a corresponding {@code ModelAndView} to forward to, or {@code null}
	 * for default processing
	 */
	ModelAndView resolveException(
			HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);

}

我们可以通过实现resolveException方法来处理我们在controller抛出的异常,通常我们返回的是一个异常处理界面,所以接口提供的返回值是一个ModelAndView。但是我们有时候可能需要返回的是json数据,如rest应用,或者微服务应用的时候,显然异常时默认返回json数据更合适。

这时为了返回json数据,我们有几种方案,一种是使用response直接输出json数据:

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		response.setContentType("application/json;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		try {
			response.getWriter().print(JSONString);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

还有一种是:

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		ModelAndView mv = new ModelAndView();
		MappingJackson2JsonView view = new MappingJackson2JsonView();
		mv.setView(view);
		mv.addObject("status", "fail");
		mv.addObject("message", "系统错误");
		return mv;
	}

显然下面这一种看起来更加舒服。

发表评论