java优雅处理自定义异常

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/wsgsm/article/details/99991782
自定义异常使用

在java项目中, 一般使用自定义异常对程序做一些特殊处理。使用自定义异常的方式,能更清楚的表现出程序中的逻辑问题。 如何优雅的使用异常,就是一门学问了。

本文采用枚举来处理自定义异常, 使用lombok生成get/set,以及构造方法

  1. 新建异常枚举类
import lombok.AllArgsConstructor;

/**
 * @ClassName: ExceptionEnum
 * @Description: TODO(异常枚举)
 * @Author: flyingkid
 * @Date: 2019-08-16 20:08:42
 */
@AllArgsConstructor
public enum ExceptionEnum {

    UNKNOWN_EXCEPTION("unknown_exception","未知异常"),

    SYSTEM_EXCEPTION("system_exception","系统异常"),

    PARAMETER_EXCEPTION("parameter_exception","参数异常");


    public final String code;

    public final String message;

}
  1. 自定义异常类,继承RuntimeException
import com.example.common.enums.ExceptionEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: ExampleException
 * @Description: TODO(自定义异常)
 * @Author: flyingkid
 * @Date: 2019-08-16 20:07:25
 */
@Data
@Slf4j
public class ExampleException extends RuntimeException{

    private static final long serialVersionUID = -6979901566637669960L;

    private ExceptionEnum exceptionEnum;

    private String code;

    private String message;


    public ExampleException(String code,String message){
        super(message);
        this.code = code;
        this.message = message;
    }

    public ExampleException(ExceptionEnum exceptionEnum){
        super(exceptionEnum.message);
        this.exceptionEnum = exceptionEnum;
    }


    public ExampleException(String code,String message,Throwable throwable){
        super(message,throwable);
        this.code = code;
        this.message = message;
    }

    public ExampleException(ExceptionEnum exceptionEnum,Throwable throwable){
        super(exceptionEnum.message,throwable);
        this.exceptionEnum = exceptionEnum;
    }


    /**
     * @description TODO 重写Throwable中printStackTrace方法,打印异常信息
     * @return void
     * @date 2019/8/21 下午7:57
     * @author flyingkid
     */
    @Override
    public void printStackTrace(){
        if (exceptionEnum != null){
            log.info("异常代码: {}, 异常信息: {}",exceptionEnum.code,exceptionEnum.message);
            return;
        }
        log.info("异常代码: {}, 异常信息: {}",code,message);
    }

}
  1. 使用
 public static void main(String[] args) {
        try {
            if (true){
                //抛出异常
                throw new ExampleException(ExceptionEnum.SYSTEM_EXCEPTION);
            }
        }catch (ExampleException e){
            //异常捕获
            e.printStackTrace();
        }
    }

控制台打印

19:36:10.678 [main] INFO com.example.common.exception.ExampleException - 异常代码: system_exception, 异常信息: 系统异常

Process finished with exit code 0

猜你喜欢

转载自blog.csdn.net/wsgsm/article/details/99991782
今日推荐