SpringBoot自定义异常+全局异常处理

使用 @ControllerAdvice和@ExceptionHandler处理全局异常

1:自定义全局异常类GlobalException

package com.myself.lucode.exception;

import com.myself.lucode.common.ResultCode;

/**
 * @Author LK
 * 自定义全局异常
 * @Date 2020/7/3
 * @Time 9:42
 */
public class GlobalException extends Throwable {
    
    private static final long serialVersionUID = -6543484989095940852L;
    private final int errorCode;
    private final String errorMsg;

    public GlobalException(ResultCode resultCode) {
        super(resultCode.getMessage());
        this.errorCode = resultCode.getCode();
        this.errorMsg = resultCode.getMessage();
    }

    public GlobalException(ResultCode resultCode, Throwable throwable) {
        super(resultCode.getMessage(), throwable);
        this.errorCode = resultCode.getCode();
        this.errorMsg = resultCode.getMessage();
    }

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

    public GlobalException(int errorCode, String errorMsg, Throwable throwable) {
        super(errorMsg, throwable);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
    }

    public int getResultCode() {
        return this.errorCode;
    }

    public String getErrorMsg() {
        return this.errorMsg;
    }
}

2:定义全局拦截异常(在类上加上@ControllerAdvice注解这个类就成为了全局异常处理类

package com.myself.lucode.handler;

import com.alibaba.fastjson.JSONObject;
import com.myself.lucode.common.CommonResult;
import com.myself.lucode.common.ResultCode;
import com.myself.lucode.exception.GlobalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author LK
 * 全局异常处理
 * @Date 2020/7/3
 * @Time 9:46
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

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

    /**
     * 处理请求方式(get,post,delete,put等)错误的异常
     */
    @ExceptionHandler(value = {HttpRequestMethodNotSupportedException.class})
    public CommonResult handlerExp(HttpRequestMethodNotSupportedException e){
        return CommonResult.failed(ResultCode.ERROR_REQUEST_TYPE.getMessage());
    }

    /**
     * 处理请求URL缺少必要参数的异常
     */
    @ExceptionHandler(value = {MissingServletRequestParameterException.class})
    public CommonResult handlerExp(MissingServletRequestParameterException e){
        return CommonResult.failed(ResultCode.NULL_PARAM.getMessage());
    }

    /**
     * 处理对象传参非空校验异常
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult handleMethodArgumentNotValid(MethodArgumentNotValidException exception) {
        List errors = exception.getBindingResult().getFieldErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.toList());
        return CommonResult.failed(JSONObject.toJSONString(errors));
    }

    /**
     * 处理自定义异常
     * @param ex
     * @return
     */
    @ExceptionHandler(GlobalException.class)
    public CommonResult bizException(GlobalException ex) {
        Logger.error("### 业务异常: {}", ex.getMessage());
        ex.printStackTrace();
        return CommonResult.failed(ex.getMessage());
    }

    /**
     * 处理Exception
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public CommonResult unknownException(Exception ex) {
        ex.printStackTrace();
        Throwable cause = ex.getCause();
        String msg;
        if (cause != null) {
            msg = cause.getMessage();
        } else {
            msg = ex.getMessage();
        }
        Logger.error("### 异常捕获: {}", msg);
        return CommonResult.failed(msg);
    }

}

3:处理请求方式(get,post,delete,put等)错误的异常(示例)

SpringBoot自定义异常+全局异常处理_第1张图片

4:处理请求URL缺少必要参数的异常(示例)

SpringBoot自定义异常+全局异常处理_第2张图片

5:处理对象传参非空校验异常(示例)

SpringBoot自定义异常+全局异常处理_第3张图片

6:处理自定义异常(示例)

SpringBoot自定义异常+全局异常处理_第4张图片

 

你可能感兴趣的:(spring,boot,java,spring,boot)