SpringBoot全局异常捕获

使用@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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容