我的 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();
我目前遇到的问题是我想从这个基本异常中创建不同的异常。例如。应从 ApplicationException 扩展的 ValidationException。
但是 build() 方法已经返回具体类型 ApplicationException。目前我被困住了,因为我不太熟悉使用泛型,甚至不知道它是否可以在异常类中使用。
最佳答案
你可以通过Class<? extends Exception>
给你的build
方法,并使用 newInstance()
在里面创建 Exception
所需类型的对象:
throw ExceptionBuilder.getBuilder("This is the general error message")
.status(404)
.code(StatusCode.RESOURCE_DOES_NOT_EXIST)
.developerMessage("The resource does not exist")
.build(ValidationException.class); // <<== Choose type here
Exception
在 build
之前不应创建对象称呼;在build
里面你可以这样做:
Exception build(Class<? extends Exception> eClass) {
Exception res = null;
try {
res = eClass.newInstance();
} catch (.......) {
// Catch the appropriate exceptions here
}
res.setAbc(); // Set values as needed
...
return res;
}
关于java - 使用构建器模式创建异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29467769/