1、全局异常
@ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody
//捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
1 @RestControllerAdvice 2 public class CustomExtHandler { 3 4 private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); 5 6 7 //捕获全局异常,处理所有不可知的异常 8 @ExceptionHandler(value=Exception.class) 9 Object handleException(Exception e,HttpServletRequest request){ 10 LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); 11 Map<String, Object> map = new HashMap<>(); 12 map.put("code", 100); 13 map.put("msg", e.getMessage()); 14 map.put("url", request.getRequestURL()); 15 return map; 16 } 17 18 }
2、自定义异常类型
自定义异常类型MyException
1 /* 2 * 功能描述: 建立自定义异常类 -- 继承运行异常最高类 3 * 4 * */ 5 6 public class MyException extends RuntimeException{ 7 8 public MyException(String code, String msg){ 9 this.code = code; 10 this.msg = msg; 11 } 12 13 private String code; 14 private String msg; 15 16 public String getCode() { 17 return code; 18 } 19 public void setCode(String code) { 20 this.code = code; 21 } 22 23 public String getMsg() { 24 return msg; 25 } 26 27 public void setMsg(String msg) { 28 this.msg = msg; 29 } 30 31 }
修改CustomExtHandler
1 @RestControllerAdvice 2 public class CustomExtHandler { 3 4 private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); 5 6 7 //捕获全局异常,处理所有不可知的异常 8 @ExceptionHandler(value=Exception.class) 9 Object handleException(Exception e,HttpServletRequest request){ 10 LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage()); 11 Map<String, Object> map = new HashMap<>(); 12 map.put("code", 100); 13 map.put("msg", e.getMessage()); 14 map.put("url", request.getRequestURL()); 15 return map; 16 } 17 18 /** 19 * 功能描述: 处理自定义异常类 20 * @return 21 * 22 */ 23 @ExceptionHandler(value = MyException.class) 24 Object handleMyException(MyException e, HttpServletRequest request){ 25 //进行页面跳转 26 // ModelAndView modelAndView = new ModelAndView(); 27 // modelAndView.setViewName("error.html"); 28 // modelAndView.addObject("msg", e.getMessage()); 29 // return modelAndView; 30 31 //f返回json数据 32 Map<String, Object> map = new HashMap<>(); 33 map.put("code", e.getCode()); 34 map.put("msg", e.getMessage()); 35 map.put("url", request.getRequestURL()); 36 return map; 37 } 38 }
模拟一个异常实现页面跳转
1 /** 2 * 功能描述: 模拟自定义异常 3 * @return 4 */ 5 @RequestMapping(value = "/api/v1/myext") 6 public Object myext() { 7 throw new MyException("500", "my ext异常"); 8 } 9
最后梳理顺序:
首先,建立自定义异常类 MyException,继承于RuntimeException。如果出异常,在@RestControllerAdvice注释下的CustomExtHandler里面捕获,根据异常种类进行处理。
异常处理的官网地址: https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling
原文地址:https://www.cnblogs.com/platycoden/p/9799900.html
时间: 2024-11-05 21:49:07