The exception interface that you try to do with a constructor with arguments is awkward to use, isn't it? That's the story.
For example, if you want to make an exception with two unique fields
@Getter
public class SampleException extends RuntimeException {
private String code;
private String id;
...
Constructor We will talk about what to prepare.
code
message
cause
It's hard to start making a constructor thinking about the combination of these.
Furthermore, since code
, ʻid, and
message` are of the same type, it is not possible to create a constructor that sets only that for each.
public SampleException(String message, String id, String code) {
super(message);
this.id = id;
this.message = message;
}
You can put Null where it doesn't fit. You might think, but it's not smart. Also, as the number of constructors increases, the user has to worry about the order, which is difficult. (If you write javadoc properly, you can understand it, but if you don't look at it one by one, you can't understand.) It's this level with two fields, so it would be disastrous if there were more fields ...
@Getter
public class SampleException extends RuntimeException {
private String code;
private String id;
private SampleException(String message, Throwable cause) {
super(message, cause);
}
public static class SampleExceptionThrower {
private String message;
private Throwable cause;
private String code;
private String id;
private SampleExceptionThrower() {
}
public static void call(Consumer<SampleExceptionThrower> consumer) {
SampleExceptionThrower builder = new SampleExceptionThrower();
consumer.accept(builder);
SampleException exception = new SampleException(builder.message, builder.cause);
exception.code = builder.code;
exception.id = builder.id;
throw exception;
}
public SampleExceptionThrower setMessage(String message) {
this.message = message;
return this;
}
public SampleExceptionThrower setCause(Throwable cause) {
this.cause = cause;
return this;
}
public SampleExceptionThrower setId(String id) {
this.id = id;
return this;
}
public SampleExceptionThrower setCode(String code) {
this.code = code;
return this;
}
}
}
Fluent Builder pattern. You can use it like this.
SampleExceptionThrower.call(builder -> builder.setCause(e)
.setMessage("message").setCode("code"));
Very clean!
I don't like the name call, so please give me some good ideas ...
Recommended Posts