java使用生成器模式创建异常?
我的java代码中有一个异常,它有几个属性可以传递到构造函数中。因此,我认为使用生成器模式创建异常会很好,因此我创建了如下异常:
public class ApplicationException extends Exception {
private static final long serialVersionUID = -8999932578270387947L;
/**
* contains redundantly the HTTP status of the response sent back to the client in case of error, so that
* the developer does not have to look into the response headers. If null a default
*/
Integer status;
/** application specific error code */
int code;
/** link documenting the exception */
String link;
/** detailed error description for developers*/
String developerMessage;
/**
*
* @param status
* @param code
* @param message
* @param developerMessage
* @param link
*/
protected ApplicationException(String message) {
super(message);
}
...
public static Builder getBuilder(String message) {
return new Builder(message);
}
public static class Builder {
private Integer status;
private int code;
private String link;
private String message;
private String developerMessage;
public Builder(String message) {
this.message = message;
}
public Builder status(int status) {
this.status = status;
return this;
}
public Builder code(int code) {
this.code = code;
return this;
}
public Builder developerMessage(String developerMessage) {
this.developerMessage = developerMessage;
return this;
}
public Builder link(String link) {
this.link = link;
return this;
}
public ApplicationException build() {
if (StringUtils.isBlank(message)) {
throw new IllegalStateException("message cannot be null or empty");
}
if (StringUtils.isBlank(link)){
link = AppConstants.API_SUPPORT_EMAIL;
}
ApplicationException created = new ApplicationException(message);
created.status = status;
created.code = code;
created.developerMessage = developerMessage;
created.link = link;
return created;
}
}
}
现在,我可以创建如下异常:
throw ApplicationException.getBuilder("This is the general error message")
.status(404)
.code(StatusCode.RESOURCE_DOES_NOT_EXIST)
.developerMessage("The resource does not exist")
.build();
我目前面临的问题是,我希望创建与此基本异常不同的异常。例如,ValidationException应该从ApplicationException扩展而来
但是build()方法已经返回了具体类型ApplicationException。目前我陷入困境,因为我不太熟悉泛型的使用,甚至不知道在异常类中是否可以使用泛型
# 1 楼答案
您可以将
Class<? extends Exception>
传递给build
方法,并使用newInstance()
inside创建所需类型的Exception
对象:在
Exception
调用之前不应创建build
对象;在build
内,您可以执行以下操作:# 2 楼答案
您要处理多少种不同的异常子类型?如果不是太多,可以在构建器中为每个异常类型创建一个
build()
方法:它不是通用的,但非常简单,可以很好地与IDE自动完成配合使用