SpringBoot基于@ControllerAdvice配置全局异常处理

版权声明:欢迎访问,本文为小编原创文章 https://blog.csdn.net/changyinling520/article/details/81431490

SpringBoot默认全局异常处理

SpringBoot提供了一个默认的映射:/error,当处理中抛出异常之后,会转到请求中处理,并且该请求有一个全局的错误页面用来展示异常内容。
启动访问一个异常的url出现的呈现的页面情况是这样的:
这里写图片描述
但是这样的页面我们也觉得不太友好,想自己设置异常的处理页面或者是展示异常处理信息,这时候我们就要用到@ControllerAdvice定义统一处理的异常处理类,而不是在每一个Controller中逐个定义。@ExceptionHandler用来定义函数针对的异常类型。

自定义全局处理异常

1.Exception对象和请求url映射到error.html中:

@ControllerAdvice
public class GlobalExceptionHandler {
   @ExceptionHandler(value = Exception.class)
    public String exceptionHandle(HttpServletRequest request, Exception e){
       return "error";
    }
}

springboot引入thymeleaf,在application.propertities设置:

spring.thymeleaf.cache=false
spring.thymeleaf.servlet.content-type=text/html
spring.thymeleaf.enabled=true
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML5
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

在src/resource/templates路径下创建error.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>错误界面</title>
</head>
<body>
您好,当前访问地址出错!
</body>
</html>

最后输出一个异常的路径如下图:
这里写图片描述

2.Exception对象和请求url返回json对象:


  • 配置全局异常处理
  • 全局异常对象
  • 返回错误结果封装

配置全局异常处理:

@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {
    @ExceptionHandler(value = Exception.class)  //处理所有的异常
    public Result<String> exceptionHandle(HttpServletRequest request, Exception e){
        e.printStackTrace();
        //将异常进行分类,不同的异常进行不同的处理
        if(e instanceof GlobalException){
            GlobalException ex=(GlobalException) e;
            return Result.error(ex.getCm());
        }else if(e instanceof BindException){
            BindException ex = (BindException)e;
            List<ObjectError> errors = ex.getAllErrors();
            ObjectError error = errors.get(0);
            String msg = error.getDefaultMessage();
            return Result.error(CodeMessage.BIND_ERROR.fillArgs(msg));
        }else {
            return Result.error(CodeMessage.SERVER_ERROR);
        }
    }
}
public class GlobalException  extends RuntimeException{
    private static final long serialVersionUID = 1L;
    private CodeMessage cm;
    public GlobalException(CodeMessage cm){
        super(cm.toString());
        this.cm=cm;
    }
    public CodeMessage getCm(){
        return cm;
    }
}

异常返回信息封装CodeMessage:

public class CodeMessage {
    private int code;
    private String message;
    //通用异常:
    public  static CodeMessage SUCCESS=new CodeMessage(0,"success");
    public  static  CodeMessage SERVER_ERROR=new CodeMessage(500,"服务端异常");
    public  static  CodeMessage  MOBILE_NOT_EXIST=new CodeMessage(400,"手机不存在");
    public  static  CodeMessage  PASSWORD_ERROR=new CodeMessage(401,"密码不正确");
    public static CodeMessage BIND_ERROR = new CodeMessage(500101, "参数校验异常:%s");

    public int getCode() {
        return code;
    }

    public CodeMessage(int code, String message) {
        this.code = code;
        this.message = message;
    }

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

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "CodeMessage{" +
                "code=" + code +
                ", message='" + message + '\'' +
                '}';
    }

    public CodeMessage fillArgs(Object... args) {
        int code = this.code;
        String message = String.format(this.message, args);
        return new CodeMessage(code, message);
    }
}

总结:
希望对你有帮助,感谢浏览!

猜你喜欢

转载自blog.csdn.net/changyinling520/article/details/81431490