欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Springboot全局异常配置超简单

程序员文章站 2024-01-16 09:12:58
...

1.创建类

package cn.cyx.common;

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 org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;


/**
 * @author cyx
 * @date 2019/10/30 11:31
 */

@ControllerAdvice
public class GlobalExceptionHandler {

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

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonResult defaultErrorHandler(HttpServletRequest req, Exception e)throws Exception{
        logger.error("",e);
        JsonResult rs = new JsonResult();
        rs.setData(e.getMessage());
        if (e instanceof  org.springframework.web.servlet.NoHandlerFoundException){
            rs.setMsg("404");
        }else{
            rs.setMsg("500");
        }
        rs.setSuccess(false);
        return rs;
    }

}

返回的实体类是自己定义的json实体类

package cn.cyx.common;

/**
 * @author cyx
 * @date 2019/7/31 17:25
 */

public class JsonResult {
    public static final JsonResult Success = new FinalResult(true);
    public static final JsonResult Fail = new FinalResult(false);
    boolean success = true;
    String msg;
    Object data;

    public void setError(String err) {
        this.msg = err;
        this.success = false;
    }

    public JsonResult() {
    }

    public JsonResult(Object data) {
        this.data = data;
    }

    public JsonResult(String err) {
        this.success = err == null || "".equals(err);
        this.msg = err;
    }

    public JsonResult(boolean success) {
        this.success = success;
    }

    public JsonResult(String err, Object data) {
        this.success = err == null || "".equals(err);
        this.data = data;
        this.msg = err;
    }

    public boolean isSuccess() {
        return this.success;
    }

    public String getMsg() {
        return this.msg;
    }

    public Object getData() {
        return this.data;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

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

    public void setData(Object data) {
        this.data = data;
    }


}

2.配置文件配置

Springboot全局异常配置超简单

3.OK测试

Springboot全局异常配置超简单