zoukankan      html  css  js  c++  java
  • springboot全局异常处理

    package video.exception;

    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RequestBody;
    import org.springframework.web.bind.annotation.ResponseBody;
    import video.dto.JsonData;


    -----------------------------异常处理类--------------------------------------------
    /**
    * 全局自定义异常处理类
    */
    @ControllerAdvice//所有异常都会被捕获
    public class GlobalExceptionHandler {

    /**
    * 处理异常
    * @return
    */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData handlerException(Exception e) {
    if (e instanceof BussinessException) {
    return JsonData.error(e.getMessage(),((BussinessException) e).getCode());
    } else if (e instanceof GlobalException ) {
    return JsonData.error(e.getMessage(),((GlobalException) e).getCode());
    } else {
    return JsonData.error("未知异常");
    }
    }

    }


    -----------------------------自定义异常类------------------------------------------
    /**
    * 全局自定义异常类
    */
    public class GlobalException extends RuntimeException {

    /**状态码*/
    private Integer code;
    /**消息提示*/
    private String msg;

    public GlobalException(Integer code, String msg) {
    super(msg);
    this.code = code;
    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 class BussinessException extends RuntimeException {

    private String msg;
    private Integer code;

    public BussinessException(Integer code, String msg) {
    super(msg);
    this.msg = msg;
    this.code = code;
    }

    public String getMsg() {
    return msg;
    }

    public void setMsg(String msg) {
    this.msg = msg;
    }

    public Integer getCode() {
    return code;
    }

    public void setCode(Integer code) {
    this.code = code;
    }
    }




  • 相关阅读:
    【Scheme归纳】3 比较do, let, loop
    【Scheme归纳】2 算数运算
    【Scheme归纳】1 使用Edwin
    【SICP练习】106 练习3.7
    【SICP练习】105 练习3.5-3.6
    【SICP练习】104 练习3.1-3.4
    【SICP练习】103 练习2.81-2.97
    【SICP练习】102 练习2.79-2.80
    【SICP练习】101 练习2.77-2.78
    【SICP练习】100 练习2.76
  • 原文地址:https://www.cnblogs.com/yuefeng123/p/11122036.html
Copyright © 2011-2022 走看看