1.0 概述
MyBatis 的异常模块,源码对应exceptions包。异常模块虽然不属于基础支持层,但是也贯穿了业务处理的各个环节。如下图:
2.0 PersistenceException
IbatisException已经被废弃。 org.apache.ibatis.exceptions.PersistenceException是MyBatis真正的异常基类。代码如下:
@Deprecated
public class IbatisException extends RuntimeException {
....省略代码
}
public class PersistenceException extends IbatisException {
private static final long serialVersionUID = -7537395265357977271L;
public PersistenceException() {
super();
}
public PersistenceException(String message) {
super(message);
}
public PersistenceException(String message, Throwable cause) {
super(message, cause);
}
public PersistenceException(Throwable cause) {
super(cause);
}
}
3.0 TooManyResultsException
org.apache.ibatis.exceptions.TooManyResultsException继承 PersistenceException类,查询返回结果过多的异常:期望返回一条,实际返回了多条。代码如下:
public class TooManyResultsException extends PersistenceException {
private static final long serialVersionUID = 8935197089745865786L;
public TooManyResultsException() {
super();
}
public TooManyResultsException(String message) {
super(message);
}
public TooManyResultsException(String message, Throwable cause) {
super(message, cause);
}
public TooManyResultsException(Throwable cause) {
super(cause);
}
}
4.0 ExceptionFactory
org.apache.ibatis.exceptions.ExceptionFactory异常工厂,用于包装异常成PersistenceException。代码如下:
public class ExceptionFactory {
private ExceptionFactory() {}
/**
* 包装异常成 PersistenceException
* @param message 消息
* @param e 发生的异常
* @return PersistenceException
*/
public static RuntimeException wrapException(String message, Exception e) {
return new PersistenceException(ErrorContext.instance().message(message).cause(e).toString(), e);
}
}
其他异常
实际上,我们会看到各个模块包下面都有其都有的异常类,代码大部分都是相同的,继承,代码如下:
public class BindingException extends PersistenceException {
private static final long serialVersionUID = 4300802238789381562L;
public BindingException() {
super();
}
public BindingException(String message) {
super(message);
}
public BindingException(String message, Throwable cause) {
super(message, cause);
}
public BindingException(Throwable cause) {
super(cause);
}
}
简单整理下:
- binding 包:BindingException
- builder 包:BuilderException、IncompleteElementException
- cache 包:CacheException
- datasource 包:DataSourceException
- executor 包:ResultMapException、ExecutorException、BatchExecutorException
- logging 包:LogException
- parsing 包:ParsingException
- plugin 包:PluginException
- reflection 包:ReflectionException
- scripting 包:ScriptingException
- session 包:SqlSessionException
- transaction 包:TransactionException
- type 包:TypeException
Java虽然提供了丰富的异常处理类,但是在项目中还会经常使用自定义异常,其主要原因是Java提供的异常类在某些情况下还是不能满足实际需球。例如以下情况:
- 1、系统中有些错误是符合Java语法,但不符合业务逻辑。
- 2、在分层的软件结构中,通常是在表现层统一对系统其他层次的异常进行捕获处理。
失控的阿甘,乐于分享,记录点滴