@ControllerAdvice的使用

 

其实@ControllerAdvice有3个作用:

  1. 全局异常处理
  2. 全局数据绑定
  3. 全局数据预处理

3.7.1 全局异常处理

就是自定义一个全局异常类,然后通过@ControllerAdvice捕获处理

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice

public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public static final String SYSTEM_ERROR = "服务器正忙,请稍后再试...";

    @ResponseBody

    @ExceptionHandler(CustomUnCheckedException.class)

    public ResultData handleryException(HttpServletRequest request, CustomUnCheckedException ex){

        logger.error("自定义异常:{}",ex);

        ResultData<String> resultData = new ResultData<>();

        resultData.setResultCode(ex.getCode());

        System.out.println(ex.getCode());

        resultData.setResultMsg(ex.getMessage());

        return resultData;

    }

    @ResponseBody

    @ExceptionHandler(Exception.class)

    public ResultData<String> handlerException(HttpServletRequest request, Exception ex){

        logger.error("异常:{}",ex);

        ResultData<String> resultData = new ResultData<>();

        resultData.setResultCode(ResultStateEnum.FAIL.getCode());

        resultData.setResultMsg(SYSTEM_ERROR);

        return resultData;

    }

}

自定义全局异常:

public class CustomUnCheckedException extends RuntimeException implements Serializable {

    private static final long serialVersionUID = 2516912856988538515L;

private static final Integer DEFAULT_CODE = 0;// 默认结果码0代表成功

private static final String DEFAULT_OUT_MSG = "成功";

private Integer code;//结果码,省略getter方法

    public String getOutMsg() {

        if (code.equals(DEFAULT_CODE)) { return getMessage();}

        CustomExceptionCodeEnum customExceptionCodeEnum = CustomExceptionCodeEnum.getByCode(code);

        if (customExceptionCodeEnum != null) {

            return customExceptionCodeEnum.getDesout();

        }

        return getMessage();

    }

 

    public String getInMsg() {

        CustomExceptionCodeEnum customExceptionCodeEnum =

CustomExceptionCodeEnum.getByCode(code);

        if (customExceptionCodeEnum != null) { return customExceptionCodeEnum.getDesin();}

        return getMessage();

    }

// 构造器 多种支持

    public CustomUnCheckedException() { super();}

    public CustomUnCheckedException(Throwable e) { super(e); }

    public CustomUnCheckedException(Integer errorCode) { this.code = errorCode; }

    public CustomUnCheckedException(CustomExceptionCodeEnum mcode, Throwable e) {

        super(mcode.getDesin(), e);

        this.code = mcode.getCode();

    }

    public CustomUnCheckedException(Integer code, Throwable e) {

        super(CustomExceptionCodeEnum.getInMsg(code), e);

        this.code = code;

    }

    public CustomUnCheckedException(Integer code, String message) {

        super(message); this.code = code;

    }

    public CustomUnCheckedException(Integer code, String message, Throwable e) {

        super(message, e);

        this.code = code;

    }

}

//错误码

public enum  CustomExceptionCodeEnum {

    DB_OPERATOR__ERROR_001(1, "数据库操作发生异常", "数据库操作发生异常"),

    SYS_NO_REPEAT_OPERATION(2, "SYS_NO_REPEAT_OPERATION", "请勿重复操作!");

    private Integer code; /**错误码*/  //省略getter

    private String desin; /** 内部描述 */

    private String desout; /** 外部描述 */

    CustomExceptionCodeEnum(Integer code, String desin, String desout) {

        this.code = code; this.desin = desin; this.desout = desout;

}

//通过错误码获取CustomExceptionCodeEnum实例

    public static CustomExceptionCodeEnum getByCode(Integer code) {

        if (null != code) {

            for (CustomExceptionCodeEnum mnum : values()) {

                if (mnum.getCode().equals(code)) { return mnum; }                

            }

        }

        return null;

    }//根据错误码获取内部描述

    public static String getInMsg(Integer code) {

        if ( null != code ) {

            for (CustomExceptionCodeEnum mnum : values()) {

                if (mnum.getCode().equals(code)) { return mnum.getDesin();}                   

            }

        }

        return null;

    }//根据错误码获取外部描述

    public static String getOutMsg(String code) {

        if (code != null && !"".equals(code.trim())) {

            for (CustomExceptionCodeEnum mnum : values()) {

                if (mnum.getCode().equals(code)) { return mnum.getDesout();}

           }

        }

        return null;

    }

}

3.7.2 全局数据绑定

定义需要绑定的数据

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ModelAttribute;

import java.util.HashMap;

import java.util.Map;

@ControllerAdvice

public class MyGlobalDataBindHandler {

    @ModelAttribute(name="allen") //对应Map的Key

    public Map<String,Object> myData(){

        Map<String, Object> map = new HashMap<>();

        map.put("age",99);//对应Map的value

        map.put("gender","男");//对应Map的value

        return map;

    }

}

测试类:

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController

public class TestController2 {

    @RequestMapping("/test2")

    public String test2(Model model){

        Map<String, Object> map = model.asMap();

        System.out.println(map);//{allen={gender=男, age=99}}

        return "test2";

    }

}

3.7.3 全局数据预处理

利用@ControllerAdvice、@InitBinder(“b”)、WebDataBinder、@ModelAttribute("b") 实现拦截并实现数据的预处理

@ControllerAdvice

public class MyGlobalDataPrecessingHandler {

    @InitBinder("b")

    public void b(WebDataBinder binder){ binder.setFieldDefaultPrefix("b."); }

    @InitBinder("a")

    public void a(WebDataBinder binder){ binder.setFieldDefaultPrefix("a."); }        

}

 

public class Author {//省略setter&getter&toString方法

    private  String name; private  Integer age;

}

 

public class Book {//省略setter&getter&toString方法

    private String name; private Double price;

}

import org.springframework.web.bind.WebDataBinder;

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.InitBinder;

测试类

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

public class TestController3 {

//http://localhost:18080/add/book?name=allen基于springboot的书&price=100&name=allen&age=28

    @RequestMapping("/add/book")

    public void addBook(Book book,Author author){

        System.out.println(book);//Book{name='allen基于springboot的书,allen', price=100.0}

        System.out.println(author);//Author{name='allen基于springboot的书,allen', age=28}

}

//http://localhost:18080/add/book2?b.name=allen基于springboot的书&b.price=100&a.name=allen&a.age=28

    @RequestMapping("/add/book2")

    public void addBook2(@ModelAttribute("b") Book book, @ModelAttribute("a")Author author){

        System.out.println(book);//Book{name='allen基于springboot的书', price=100.0}

        System.out.println(author);//Author{name='allen', age=28}

    }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值