Exception 全局统一处理

139 阅读1分钟

自定义异常类

@EqualsAndHashCode(callSuper = true)
@Data
public class BizException extends RuntimeException {

    private String errorCode;
    private String errorMessage;

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

错误枚举接口

public interface BaseErrorInfo {

    String getErrorCode();

    String getErrorMessage();

    default void assertTrue(boolean condition, String... params) throws BizException {
        if (!condition) {
            String errorMessage = this.getErrorMessage();
            if (params != null && params.length > 0) {
                errorMessage = String.format(errorMessage, params);
            }

            throw new BizException(this.getErrorCode(), errorMessage);
        }
    }
}

错误枚举实现类

@AllArgsConstructor
public enum BaseErrorEnum implements BaseErrorInfo {

    SUCCESS("10000", "成功"),
    FAIL("10001", "失败 %s "),
    ;

    private final String errorCode;
    private final String errorMessage;

    @Override
    public String getErrorCode() {
        return errorCode;
    }

    @Override
    public String getErrorMessage() {
        return errorMessage;
    }
}

异常切面

@Slf4j
@RestControllerAdvice
public class GlobalExceptionAdvice {

    @ExceptionHandler(value = BizException.class)
    public CommonResponse<Void> bizExceptionHandler(BizException ex) {
        return new CommonResponse<>(Integer.valueOf(ex.getErrorCode()), ex.getErrorMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public CommonResponse<String> handlerException(Exception ex) {
        return new CommonResponse<>(-1, ex.getMessage());
    }
}

控制层

@Slf4j
@RestController
@RequestMapping("/test")
public class TestController {

    @GetMapping("/biz-exception")
    public void runtimeException() {
        BaseErrorEnum.FAIL.assertTrue(true == false, "自定义异常");
    }
}

测试

image.png