DAO层的异常处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40178464/article/details/81639456

如果不考虑上层代码对于数据层的使用,在数据层出现的异常一般用声明或捕获不处理的方式进行标记,但是当service层对数据进行使用时,将无法寻找到异常并处理,所以在数据层应该对异常进行一些处理,处理模式如下:
在DAO层建立一个RuntimeException的子类,专门用于异常处理,该类只需有固定的序列号并利用构造器生成方法即可:

public class DaoException extends RuntimeException {
    private static final long serialVersionUID = -1770510730768385681L;

    public DaoException() {
    }

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

    public DaoException(String message, Throwable cause) {
        super(message, cause);
    }

    public DaoException(Throwable cause) {
        super(cause);
    }

    public DaoException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

对于异常就可以包装处理了:

        try {
            //code
        } catch (SQLException e) {
            // 包装异常
            throw new DaoException(e.getMessage(), e);
        } finally {
            //code
        }

猜你喜欢

转载自blog.csdn.net/qq_40178464/article/details/81639456