2023年11月29日发(作者:)
MyBatis框架之异常处理
MyBatis框架定义了许多的异常类,之所以定义这么多的异常类,应该是将每⼀种异常情况都独⽴出来,这样在出现异常时,定位就很
明确了。⽽我们平时写代码时,都是瞎搞⼀通,异常类⼤多也是随便定义,或者是使⽤JDK⾃带异常类,有时候甚⾄是直接弄Exception。
缺点显⽽易见了。今后写代码,也应该是学着MyBatis,将每种业务(或场景)可能出现的异常进⾏单独封装,这样,当项⽬报错,出现异
常时,定位起来也就简单很多。
MyBatis的异常爹是 ,⽽它⼜是RuntimeException的⼉⼦。这是为什么呢?
1. Exception异常,要么抛,要么处理。。。强制性要求。。。
2. RuntimeException异常,编译时我也不知道会不会出错,运⾏时才知道结果咋样,,,, 可以不处理,但是出错了,程序就停
摆。
具体啥原因,我也不知道,但是⼈家MyBatis都是这样搞,那我们以后写代码也跟着这样弄吧
public class IbatisException extends RuntimeException {
private static final long serialVersionUID = 3880511L;
public IbatisException() {
super();
}
public IbatisException(String message) {
super(message);
}
public IbatisException(String message, Throwable cause) {
public class ExceptionFactory {
private ExceptionFactory() {
// Prevent Instantiation
}
public static RuntimeException wrapException(String message, Exception e) {
return new PersistenceException(ce().message(message).cause(e).toString(), e);
}
}
私有化构造器,但然后通过静态⽅法,将异常信息和异常真实对象创建出来。
注意: 返回的异常类型是, ⽽ new 的是。 在⾼版本的MyBatis中将
标注为过时类,⽽ 却⼜是的⼦类。。。。。 这似乎是⼀种代
码扩展/升级/兼容⽼版本的⽅式呢
不过,我觉得中,最关键是应该是ce().message(message).cause(e).toString()这句
代码了。 下⾯我们来看看
2.
public class ErrorContext {
private static final String LINE_SEPARATOR = perty("tor","n");
private static final ThreadLocal
private ErrorContext stored;
private String resource;
private String activity;
private String object;
private String message;
private String sql;
private Throwable cause;
private ErrorContext() {
}
public static ErrorContext instance() {
ErrorContext context = ();
if (context == null) {
}
public ErrorContext resource(String resource) {
this.resource = resource;
return this;
}
public ErrorContext activity(String activity) {
this.activity = activity;
return this;
}
public ErrorContext object(String object) {
this.object = object;
return this;
}
public ErrorContext message(String message) {
this.message = message;
return this;
}
public ErrorContext sql(String sql) {
this.sql = sql;
return this;
}
public ErrorContext cause(Throwable cause) {
this.cause = cause;
return this;
}
public ErrorContext reset() {
resource = null;
activity = null;
(object);
}
// activity
if (activity != null) {
(LINE_SEPARATOR);
("### The error occurred while ");
(activity);
}
// activity
if (sql != null) {
(LINE_SEPARATOR);


发布评论