SpringMVC异常处理注解@ExceptionHandler
关于@ExceptionHandler注解不详细说明,次记录仅供参考,直接贴项目中的代码用法,不喜勿喷,不足之处请指点。
Controller:
1.controller继承异常基类BaseController
1 public class BaseController { 2 3 protected Logger logger = LoggerFactory.getLogger(getClass()); 4 5 @ExceptionHandler 6 public @ResponseBody Object exceptionHandler(Exception exception, HttpServletResponse response) { 7 if (exception instanceof BException) { 8 exception.printStackTrace(); 9 logger.error(exception.getMessage()); 10 return JsonResult.error(((BException) exception).getMsg()); 11 }else { 12 exception.printStackTrace(); 13 logger.error(exception.getMessage()); 14 return JsonResult.error("系统发生错误。"); 15 } 16 } 17 18 }
BException:
2.自定义异常BException,继承RuntimeException
1 public class BException extends RuntimeException{ 2 private static final long serialVersionUID = 1L; 3 private String msg;//错误消息 4 private boolean async; //是否异步 5 6 public BException(){ 7 super(); 8 } 9 10 public BException(String msg) { 11 super(msg); 12 this.async = false; 13 this.msg = msg; 14 } 15 16 public BException(Exception e){ 17 super(e.getMessage()); 18 this.async = false; 19 if(e instanceof BException){ 20 BException self = (BException) e; 21 this.msg = self.getMsg(); 22 }else{ 23 this.msg = e.getMessage(); 24 } 25 26 } 27 28 public String getMsg() { 29 return msg; 30 } 31 32 public void setMsg(String msg) { 33 this.msg = msg; 34 } 35 36 public boolean isAsync() { 37 return async; 38 } 39 40 public void setAsync(boolean async) { 41 this.async = async; 42 } 43 }
Service:
3.在service层直接使用自定义的异常类,将异常抛出到controller,因为controller继承异常基类BaseController ,所以service中相关的异常BaseController会处理
1 public Map<String, Object> findRank(String account) throws BException{ 2 List<Map<String, Object>> list = dao.findRank(account); 3 if(list == null || list.isEmpty()) 4 throw new BException("未找到再生值排名"); 5 6 Map<String, Object> map = list.get(0); 7 return map; 8 }