我有一個例外,在我的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。目前我被卡住了,因爲我不熟悉使用泛型,如果它甚至可以在異常類中使用。
你需要編譯時間類型爲'ValidationException',還是隻關心執行時間類型? – 2015-04-06 08:25:52
我認爲在執行時間就足夠了,如果它讓思考更容易。我只是不想只使用一種通用的異常類型。我想指出,在對象的驗證過程中,某些東西向南.. – daniel 2015-04-06 08:31:08
使用更多[高級構建器模式](http://programmers.stackexchange.com/questions/228939/how-to-improve-upon-blochs-建設者模式對做-IT-更合適的使用)。爲了獲得靈感,請看Spring的['HttpConfiguration'](http://docs.spring.io/autorepo/docs/spring-security-javaconfig-build/1.0.0.CI-SNAPSHOT/api-reference/org/springframework /security/config/annotation/web/HttpConfiguration.html)。 – 2015-04-06 08:32:19