栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot全局异常处理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot全局异常处理

SpringBoot中有一个ControllerAdvice注解,表示已开启 全局异常捕获

首先:

@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(value =Exception.class)
	public String exceptionHandler(Exception e){
		System.out.println("未知异常!原因是:"+e);
       	return e.getMessage();
    }
}

该示例可对捕获的异常进行简单二次处理,返回异常信息,但对于我们开发人员来说不够人性化,可自定义异常:

上代码:

public interface baseErrorInfoInterface {
    
	 String getResultCode();
	
	
	 String getResultMsg();
}
package com.example.datafile.exception;

public class BizException extends RuntimeException{

    private static final long serialVersionUID = 1L;

    
    protected String errorCode;
    
    protected String errorMsg;

    public BizException() {
        super();
    }

    public BizException(baseErrorInfoInterface errorInfoInterface) {
        super(errorInfoInterface.getResultCode());
        this.errorCode = errorInfoInterface.getResultCode();
        this.errorMsg = errorInfoInterface.getResultMsg();
    }

    public BizException(baseErrorInfoInterface errorInfoInterface, Throwable cause) {
        super(errorInfoInterface.getResultCode(), cause);
        this.errorCode = errorInfoInterface.getResultCode();
        this.errorMsg = errorInfoInterface.getResultMsg();
    }

    public BizException(String errorMsg) {
        super(errorMsg);
        this.errorMsg = errorMsg;
    }

    public BizException(String errorCode, String errorMsg) {
        super(errorCode);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public BizException(String errorCode, String errorMsg, Throwable cause) {
        super(errorCode, cause);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }


    public String getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(String errorCode) {
        this.errorCode = errorCode;
    }

    public String getErrorMsg() {
        return errorMsg;
    }

    public void setErrorMsg(String errorMsg) {
        this.errorMsg = errorMsg;
    }

    @Override
    public String getMessage() {
        return errorMsg;
    }

    @Override
    public Throwable fillInStackTrace() {
        return this;
    }
}

package com.example.datafile.exception;

import com.example.datafile.common.api.CommonResult;
import com.example.datafile.common.api.ResultCode;
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 javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class GlobalExceptionHandler {

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

    
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public CommonResult bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("【业务异常!】{}", e.getErrorMsg());
        return CommonResult.error(e.getErrorCode(), e.getErrorMsg());
    }

    
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public CommonResult exceptionHandler(HttpServletRequest req, NullPointerException e) {
        logger.error("【空指针异常!】", e);
        return CommonResult.error(ResultCode.BODY_NOT_MATCH);
    }


    
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResult exceptionHandler(HttpServletRequest req, Exception e) {
        logger.error("【全局异常!】", e);
        return CommonResult.error(ResultCode.INTERNAL_SERVER_ERROR);
    }
}

自定义数据格式

package com.example.datafile.common.api;

import com.example.datafile.exception.baseErrorInfoInterface;


public class CommonResult {
    private String version;

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getTraceId() {
        return traceId;
    }

    public void setTraceId(String traceId) {
        this.traceId = traceId;
    }

    private String code;
    private String msg;
    private String traceId;
    private T data;

    public CommonResult() {
    }

    public CommonResult(String code, String message) {
        this.code = code;
        this.msg = message;
    }

    public CommonResult(String code, String message, T data) {
        this.code = code;
        this.msg = message;
        this.data = data;
    }

    public CommonResult(String version, String code, String message,String traceId, T data) {
        this.code = code;
        this.msg = message;
        this.data = data;
    }

    
    public static  CommonResult success(T data) {
        return new CommonResult(ResultVersion.version,ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),ResultVersion.traceId, data);
    }

    
    public static  CommonResult success(T data, String message) {
        return new CommonResult(ResultVersion.version,ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),ResultVersion.traceId, data);
    }

    
    public static  CommonResult failed(ResultCode resultCode) {
        return new CommonResult(resultCode.getCode(), resultCode.getMessage(), null);
    }

    
    public static  CommonResult failed(String message) {
        return new CommonResult<>(ResultCode.INTERNAL_SERVER_ERROR.getCode(), message, null);
    }

    
    public static  CommonResult error(String code, String message) {
        return new CommonResult<>(code, message, null);
    }

    
    public static  CommonResult error(baseErrorInfoInterface errorInfo) {
        return new CommonResult<>(errorInfo.getResultCode(), errorInfo.getResultMsg(), null);
    }

    
    public static  CommonResult error( String message) {
        return new CommonResult<>("-1", message, null);
    }

    
    public static  CommonResult failed() {
        return failed(ResultCode.INTERNAL_SERVER_ERROR);
    }


    public String getCode() {
        return code;
    }

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

    public String getMsg() {
        return msg;
    }

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

    public T getData() {
        return data;
    }

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

示例

if (Objects.isNull(formId)) {
            throw new BizException(ExceptionEnum.NOT_EMPTY_PARAMS.getValue());
        }
//根据表单Id获取表单内容
    @Test
    public void getFormInfoTest() {
        CommonResult commonResult = formController.getFormInfo(null);
        System.out.println(commonResult);
    }

测试方法,故意不传参数,测试结果如下:

成功捕获到异常!

参考文章
https://www.cnblogs.com/xuwujing/p/10933082.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/281904.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号