spring Add boot2.0 + capture the global exception

1, add custom exception, inherited RuntimeException, Why inherited RuntimeException it? Because our transaction rollback occurs under RuntimeException exception.

 1 public class BusinessException extends RuntimeException{
 2 
 3     public BusinessException(String code, String msg){
 4         this.code = code;
 5         this.msg = msg;
 6     }
 7 
 8     private String code;
 9     private String msg;
10 
11     public String getCode() {
12         return code;
13     }
14     public void setCode(String code) {
15         this.code = code;
16     }
17 
18     public String getMsg() {
19         return msg;
20     }
21 
22     public void setMsg(String msg) {
23         this.msg = msg;
24     }
25 
26 }
Custom exception class

2, add a global exception caught, use annotations to achieve @RestControllerAdvice

 1 public class CustomExtHandler {
 2 
 3     private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
 4 
 5 
 6     //捕获全局异常,处理所有不可知的异常
 7     @ExceptionHandler(value=Exception.class)
 8     Object handleException(Exception e,HttpServletRequest request){
 9         LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
10         Map<String, Object> map = new HashMap<>();
11         map.put("code", 100);
 12 is          map.put ( "MSG" , e.getMessage ());
 13 is          map.put ( "URL" , request.getRequestURL ());
 14          return Map;
 15      }
 16  
. 17      / ** 
18 is       * Description: processing custom exception class
 . 19       * @return 
20 is       *
 21 is       * / 
22 is      @ExceptionHandler (value = BusinessException. class )
 23 is      Object handleMyException (BusinessException E, the HttpServletRequest Request) {
 24          // F json data returns 
25          the Map <String, Object> Map = new new HashMap<>();
26         map.put("code", e.getCode());
27         map.put("msg", e.getMsg());
28         map.put("url", request.getRequestURL());
29         return map;
30     }
Global exception caught

3, using

1  the throw  new new BusinessException ( "200", "wrong ah!");

 

Guess you like

Origin www.cnblogs.com/rolayblog/p/11237259.html