标签:springmvc
在SpringMVC捕获异常只需要实现接口org.springframework.web.servlet.HandlerExceptionResolver,即可自定义返回异常,如:属性转换异常
@RequestMapping("/test") @ResponseBody public String str(Integer age) throws Exception { return "test:" + age; }
package com.cml.mvc.exception; import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.TypeMismatchException; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import com.cml.mvc.beans.Result; import com.google.gson.Gson; public class MyExceptionHandler implements HandlerExceptionResolver { private static Log log = LogFactory.getLog(MyExceptionHandler.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { log.info("异常捕获=======>" + ex); log.info("异常捕获=======>" + handler); Result result = new Result(); // 返回错误信息不为空 if (ex instanceof TypeMismatchException && null != ex.getMessage()) { result.setResult(ex.getMessage()); } else { result.setResult("500 服务器异常!"); } response.setHeader("content-type", "application/json"); response.setCharacterEncoding("UTF-8"); try { Writer writer = response.getWriter(); writer.write(new Gson().toJson(result)); writer.close(); } catch (IOException e1) { e1.printStackTrace(); } return null; } }
设想:如果可以获取到所有类型转换错误信息,那是多perfect啊,研究中。。。。
标签:springmvc
原文地址:http://blog.csdn.net/cml_blog/article/details/45271261