@ExceptionHandler处理异常,在controller层写以下方法,返回前端的结果为{"msg":"Exception"},如果模板引擎是thymeleaf则可以return一个String字符串跳转到templates页面
或者另外新建一个处理器类添加@ControllerAdvice注解,并写以下方法
@ExceptionHandler(value = {Exception.class})
@ResponseBody
public Map ExceptionHandler(Exception e){
Map map = new HashMap();
map.put("msg","Exception");
return map;
}
在@Configuration修饰的Java配置类中添加以下代码
@Bean
public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){
SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
Properties properties = new Properties();
properties.setProperty("java.lang.Exception","index"); //表示发生Exception异常时跳转到templates下的index页面
simpleMappingExceptionResolver.setExceptionMappings(properties);
return simpleMappingExceptionResolver;
}
实现HandlerExceptionResolver接口
@Component
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
System.out.println("全局的自定义异常处理被触发...");
ModelAndView modelAndView = new ModelAndView(); //要返回ModelAndView对象,不能返回null
Map map = new HashMap();
if(e instanceof NullPointerException){ //如果发生空指针异常的处理
map.put("Exception", e.toString());
map.put("msg","find exception");
JSON parse = JSONUtil.parseObj(map, false);
try {
httpServletResponse.getWriter().write(parse.toString()); //map序列化成json返回给浏览器
} catch (IOException ex) {
ex.printStackTrace();
}
}
return modelAndView;
}
}