在SpringMVC捕获异常只需要实现接口org.springframework.web.servlet.HandlerExceptionResolver,即可自定义返回异常,如:属性转换异常
@RequestMapping("/test") @ResponseBody public String str(Integer age) throws Exception { return "test:" + age; }
如果调用方法时传入参数age=abc此时会抛出TypeMismatchException,在自定义的异常捕获中,只需要根据信息进行返回:
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啊,研究中。。。。
时间: 2024-11-29 07:09:12