现在的位置: 首页 > 综合 > 正文

Spring 注解学习手札(八)补遗——@ExceptionHandler

2018年05月20日 ⁄ 综合 ⁄ 共 1046字 ⁄ 字号 评论关闭

直接上代码: 

Java代码  收藏代码
  1. @Controller  
  2. public class AccessController {  
  3.   
  4.     /** 
  5.      * 异常页面控制 
  6.      *  
  7.      * @param runtimeException 
  8.      * @return 
  9.      */  
  10.     @ExceptionHandler(RuntimeException.class)  
  11.     public @ResponseBody  
  12.     Map<String,Object> runtimeExceptionHandler(RuntimeException runtimeException) {  
  13.         logger.error(runtimeException.getLocalizedMessage());  
  14.   
  15.         Map model = new TreeMap();  
  16.         model.put("status"false);  
  17.         return model;  
  18.     }  
  19.   
  20. }  



当这个Controller中任何一个方法发生异常,一定会被这个方法拦截到。然后,输出日志。封装Map并返回,页面上得到status为false。就这么简单。 

或者这个有些有些复杂,来个简单易懂的,上代码: 

Java代码  收藏代码
  1. @Controller  
  2. public class AccessController {  
  3.     /** 
  4.      * 异常页面控制 
  5.      *  
  6.      * @param runtimeException 
  7.      * @return 
  8.      */  
  9.     @ExceptionHandler(RuntimeException.class)  
  10.     public String runtimeExceptionHandler(RuntimeException runtimeException,  
  11.             ModelMap modelMap) {  
  12.         logger.error(runtimeException.getLocalizedMessage());  
  13.   
  14.         modelMap.put("status", IntegralConstant.FAIL_STATUS);  
  15.         return "exception";  
  16.     }  
  17. }  

抱歉!评论已关闭.