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);

    /**
     * 处理自定义的业务异常
     *
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public CommonResult bizExceptionHandler(HttpServletRequest req, BizException e) {
        logger.error("【业务异常!】{}", e.getErrorMsg());
        return CommonResult.error(e.getErrorCode(), e.getErrorMsg());
    }

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


    /**
     * 处理其他异常
     *
     * @param req
     * @param e
     * @return
     */
    @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<T> {
    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;
    }

    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     */
    public static <T> CommonResult<T> success(T data) {
        return new CommonResult<T>(ResultVersion.version,ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),ResultVersion.traceId, data);
    }

    /**
     * 成功返回结果
     *
     * @param data 获取的数据
     * @param  message 提示信息
     */
    public static <T> CommonResult<T> success(T data, String message) {
        return new CommonResult<T>(ResultVersion.version,ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(),ResultVersion.traceId, data);
    }

    /**
     * 失败返回结果
     * @param resultCode 错误码
     */
    public static <T> CommonResult<T> failed(ResultCode resultCode) {
        return new CommonResult<T>(resultCode.getCode(), resultCode.getMessage(), null);
    }

    /**
     * 失败返回结果
     * @param message 提示信息
     */
    public static <T> CommonResult<T> failed(String message) {
        return new CommonResult<>(ResultCode.INTERNAL_SERVER_ERROR.getCode(), message, null);
    }

    /**
     * 失败
     */
    public static <T> CommonResult<T> error(String code, String message) {
        return new CommonResult<>(code, message, null);
    }

    /**
     * 失败
     */
    public static <T> CommonResult<T> error(BaseErrorInfoInterface errorInfo) {
        return new CommonResult<>(errorInfo.getResultCode(), errorInfo.getResultMsg(), null);
    }

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

    /**
     * 失败返回结果
     */
    public static <T> CommonResult<T> 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);
    }

测试方法,故意不传参数,测试结果如下:
在这里插入图片描述
成功捕获到异常!

工作原理
注解使用:
@ControllerAdvice 注解可以应用于任何类,表明该类包含一个或多个全局异常处理器方法。
这些处理器方法通常会带有 @ExceptionHandler 注解,该注解指定了它们可以处理的异常类型。
请求处理:
当一个 HTTP 请求到达 Spring 应用时,Spring MVC 的 DispatcherServlet 负责分发请求到相应的控制器方法。
如果在请求处理过程中发生异常,Spring 会检查是否有任何 @ControllerAdvice 注解的类可以处理该异常。
异常处理:
Spring 会查找与抛出异常类型相匹配的 @ExceptionHandler 方法。这包括直接匹配的异常类型以及它的超类型。
找到匹配的 @ExceptionHandler 方法后,Spring 会调用该方法来处理异常。这通常涉及返回一个特定的 HTTP 状态码和/或响应体,以便向客户端报告错误。
响应生成:
@ExceptionHandler 方法可以返回一个视图名、ModelAndView 对象、ResponseEntity 对象,或者直接返回一个对象,后者会被序列化为 HTTP 响应体。
返回值可以携带错误信息、HTTP 状态码和其他响应头信息,以便客户端能够正确解析和处理错误。

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值