Spring Boot Learning Sharing (3) - Implementation of Global Exception Monitoring


Spring Boot implements global exception monitoring and can handle both ajax and web requests


Spring Boot provides two annotations @ControllerAdvice and @RestControllerAdvice to implement global exception monitoring, and then use the @ExceptionHandler annotation to indicate the type of exception to be monitored. Here, in order to achieve the same type of exception to handle web and ajax requests, use @RestControllerAdvice

Here, a defined exception class is defined DescribeException, including self-defined exceptions, and an exception enumeration class is also defined to ExceptionEnumstore self-defined exceptions. When an exception is thrown , the class that throws is thrown DescribeExceptioninstead, thus simplifying exception handlingExceptionHandle

ExceptionHandle .class

@RestControllerAdvice
public class ExceptionHandle {

    @ExceptionHandler(value = Exception.class)
    public Object exceptionGet(Exception e,HttpServletRequest request,HttpServletResponse response) {
        //自定义的异常类
        DescribeException MyException = null;
        //返回前端的数据格式
        Result<?> result = null;
        //判断异常是否属于已定义
        if (e instanceof DescribeException) {
            MyException = (DescribeException) e;
            result =  ResultUtil.error(MyException.getCode(), MyException.getMessage());
        }
        //其它再拦截器以及其它无法直接抛出异常的地方抛出的异常只能自己判断,类似与shiro的权限不足异常
        else if (e instanceof UnexpectedTypeException) {

        }
        //上传文件过大异常
        else if (e instanceof UnauthorizedException) {
            result =  ResultUtil.error(ExceptionEnum.UnauthorizedException);
        }
        //不属于以上所有异常,按未定义异常处理
        else {
            result = ResultUtil.error(ExceptionEnum.UNKNOW_ERROR);
        }
        //判断是否为ajax请求,是则返回json格式数据,不是则返回ModelAndView对象
        if(isAjax(request)) {
            return result;
        }
        else {
            ModelAndView mav = new ModelAndView("error");
            mav.addObject("error",result.getMsg());
            return mav;
        }
    }

    //判断是否为ajax请求
    boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
    }
}

DescribeException.class

public class DescribeException extends RuntimeException{

    //错误状态码
    private Integer code;

    //利用定义的枚举类初始化
    public DescribeException(ExceptionEnum exceptionEnum) {
        super(exceptionEnum.getMsg());
        this.code = exceptionEnum.getCode();
    }

    //自定义异常
    public DescribeException(String message, Integer code) {
        super(message);
        this.code = code;
    }

ExceptionEnum.class

public enum ExceptionEnum {
    UNKNOW_ERROR(-1,"未知错误"),
    USER_IS_EXIT(-101,"用户已存在"),
    AccountIsLocked(1,"账户已被锁定,请60秒以后重试"),
    UnauthorizedException(2,"无访问权限")
;

    private Integer code;

    private String msg;

    ExceptionEnum(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

(A practical tip is attached at the end)

Generally, the file configuration when going online is different from the configuration during testing. At this time, in order to prevent frequent changes to the content of the yml file, you can set multiple configuration files, such as: application-xxx
. .yml add:

spring:
    profiles:
        active: dev

Switch between different yml files: add: after the
command when running--spring.profiles.active=xxx


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325485294&siteId=291194637