BusinessException自定义业务异常,GlobalExceptionHandler 全局异常,常见异常类型拦截处理

package com.csw.mybatisSpringboot.config.exception;

/**
 * 自定义异常

 *抛异常的时候一定要用throw new BusinessException("XXX"); 不能return  new BusinessException("XXX");

 */
public class BusinessException extends RuntimeException {
    private int errorCode;

    public BusinessException(String message) {
        super(message);
    }

    public BusinessException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }

    public BusinessException(int errorCode, String message, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
    }

    public int getErrorCode() {
        return errorCode;
    }
}

package com.csw.shuanfa.GlobalConfig.exception;


import com.csw.mysqldate.exception.BusinessException;
import com.csw.mysqldate.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.ObjectError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【全局异常处理】
 * 注意这边是RestControllerAdvice  不是ControllerAdvice
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @Autowired
    private HttpServletRequest httpServletRequest;
    Logger log = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Throwable.class)
    public Result<String> handleException(Throwable e) {
        // 在这里可以进行异常处理逻辑,例如记录日志、发送错误报告等
        String requestURI = httpServletRequest.getRequestURI();

        /**
         * 比如get请求用post进行调用
         */
        if (e instanceof HttpRequestMethodNotSupportedException) {
            log.error("请求地址'{}',【请求方式不被允许】'{}'", requestURI, e);
            return Result.err("请求方式不被允许" + e.getMessage());
        }

        /**
         * 参数入参检查异常,比如用了@Notnull
         */
        if (e instanceof MethodArgumentNotValidException) {
            List<ObjectError> allErrors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
            List<String> strList = allErrors.stream().map(c -> c.getDefaultMessage()).collect(Collectors.toList());
            log.error("请求地址'{}',【参数入参检查异常】'{}'", requestURI, e);
            return Result.err("参数入参检查异常" + strList.toString());
        }

        /**
         * Exception下
         * RuntimeException下
         * 自定义业务异常
         */
        if (e instanceof BusinessException) {
            log.error("请求地址'{}',【业务异常】'{}'", requestURI, e);
            return Result.err("业务异常" + e.getMessage());
        }

        /**
         * Exception下
         * RuntimeException下
         * 空指针异常
         */
        if (e instanceof NullPointerException) {
            log.error("请求地址'{}',【空指针异常】'{}'", requestURI, e);
            return Result.err("空指针异常" + e.getMessage());
        }

        /**
         * Exception下
         *  RuntimeException下
         *  IndexOutOfBoundsException下
         * 数组越界异常
         */
        if (e instanceof ArrayIndexOutOfBoundsException) {
            log.error("请求地址'{}',【数组越界异常】'{}'", requestURI, e);
            return Result.err("数组越界异常" + e.getMessage());
        }


        /**
         * Exception下
         * RuntimeException下
         * 类型转换异常
         */
        if (e instanceof ClassCastException) {
            log.error("请求地址'{}',【类型转换异常】'{}'", requestURI, e);
            return Result.err("类型转换异常" + e.getMessage());
        }

        /**
         * Exception下
         * RuntimeException下
         * 算术异常
         */
        if (e instanceof ArithmeticException) {
            log.error("请求地址'{}',【算术异常】'{}'", requestURI, e);
            return Result.err("算术异常" + e.getMessage());
        }

        /**
         * Exception下
         * IOException下
         * 文件未找到异常
         */
        if (e instanceof FileNotFoundException) {
            log.error("请求地址'{}',【文件未找到异常】'{}'", requestURI, e);
            return Result.err("文件未找到异常" + e.getMessage());
        }

        /**
         * Exception下
         * IOException下
         * 文件结束异常
         */
        if (e instanceof EOFException) {
            log.error("请求地址'{}',【文件结束异常】'{}'", requestURI, e);
            return Result.err("文件结束异常" + e.getMessage());
        }
        /**
         * Exception下
         * ReflectiveOperationException下
         * 类未找到异常
         */
        if (e instanceof ClassNotFoundException) {
            log.error("请求地址'{}',【类未找到异常】'{}'", requestURI, e);
            return Result.err("类未找到异常" + e.getMessage());
        }

        /**
         * Exception下
         * 数据库异常
         */
        if (e instanceof SQLException) {
            log.error("请求地址'{}',【数据库异常】'{}'", requestURI, e);
            return Result.err("数据库异常" + e.getMessage());
        }
        /**
         * Exception下
         * 并发异常
         */
        if (e instanceof InterruptedException) {
            log.error("请求地址'{}',【并发异常】'{}'", requestURI, e);
            return Result.err("并发异常" + e.getMessage());
        }

        /**
         * 错误
         */
        if (e instanceof Error) {
            log.error("请求地址'{}',【系统发生严重错误】'{}'", requestURI, e);
            return Result.err("系统发生严重错误" + e.getMessage());
        }

        //放最后
        log.error("请求地址'{}',【异常】'{}'", requestURI, e);
        return Result.err("异常" + e.getMessage());

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容