美文网首页
SpringBoot全局异常捕获

SpringBoot全局异常捕获

作者: JFang | 来源:发表于2018-05-05 11:23 被阅读0次

    使用@ControllerAdvice注解,将Controller中未使用try-catch捕获异常的,进行统一处理,
    建立GlobalExceptionHandler类使用@ControllerAdvice注解

    @ControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(Exception.class)
        @ResponseBody
        public Map<String,Object> handlerException(){
            Map<String,Object> map = new HashMap<>();
            map.put("code",500);
            map.put("msg","系统繁忙,请稍后重试");
            return map;
        }
    
        @ExceptionHandler(BusinessException.class)
        @ResponseBody
        public Map<String,Object> handlerBusinessException(BusinessException businessException){
            Map<String,Object> map = new HashMap<>();
            map.put("code",businessException.getCode());
            map.put("msg",businessException.getMsg());
            map.put("desc",businessException.getDesc());
            return map;
        }
    
        @ExceptionHandler(SQLException.class)
        @ResponseBody
        public Map<String,Object> handlerSQLException(){
            Map<String,Object> map = new HashMap<>();
            return map;
        }
    }
    

    其中BusinessException是业务定制异常,在使用过程中可以直接抛出异常。如下:

    @RequestMapping("/home2")
        @ResponseBody
        String getProductData2() throws BusinessException {
            throw new BusinessException(500,"系统异常","系统走神了");
        }
    

    下边是业务异常定制的实体,可根据业务需求定制:

    /**
     * 业务异常
     */
    public class BusinessException extends Exception{
        /*异常处理编码*/
        private Integer code;
        /*异常处理信息*/
        private String msg;
        /*异常处理描述*/
        private String desc;
    
        public BusinessException(Integer code, String msg, String desc) {
            this.code = code;
            this.msg = msg;
            this.desc = desc;
        }
    
        public BusinessException(String msg) {
            this.msg = msg;
        }
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public void setDesc(String desc) {
            this.desc = desc;
        }
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot全局异常捕获

          本文链接:https://www.haomeiwen.com/subject/fsmsrftx.html