@ExceptionHandler處理異常,在controller層寫以下方法贝淤,返回前端的結(jié)果為{"msg":"Exception"},如果模板引擎是thymeleaf則可以return一個(gè)String字符串跳轉(zhuǎn)到templates頁面
或者另外新建一個(gè)處理器類添加@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");? //表示發(fā)生Exception異常時(shí)跳轉(zhuǎn)到templates下的index頁面
? ? simpleMappingExceptionResolver.setExceptionMappings(properties);
? ? return simpleMappingExceptionResolver;
}
實(shí)現(xiàn)HandlerExceptionResolver接口
@Component
public class MyHandlerExceptionResolver implements HandlerExceptionResolver {
? ? @Override
? ? public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)? {
? ? ? ? System.out.println("全局的自定義異常處理被觸發(fā)...");
? ? ? ? ModelAndView modelAndView = new ModelAndView();? ? //要返回ModelAndView對象政供,不能返回null
? ? ? ? Map map = new HashMap();
? ? ? ? if(e instanceof NullPointerException){? ? ? ? ? ? //如果發(fā)生空指針異常的處理
? ? ? ? ? ? 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;
? ? }
}