'How to write custom excetion for Mutilple exceptions in java?
I am using smtp api which throws MessageException and IOException
But in our application, we need to have wrapper exception for both.
Is it possible to write wrapper exception for this? like custom exception?
Solution 1:[1]
Consider to create a root Exception container as
public class GeneralExceptionContainer extends RuntimeException{
private Integer exceptionCode;
private String message;
public GeneralExceptionContainer(String argMessage, Integer exceptionCode) {
super(argMessage);
this.exceptionCode = exceptionCode;
this.message = argMessage;
}
public GeneralExceptionContainer(Throwable cause, Integer exceptionCode, String argMessage) {
super(argMessage, cause);
this.exceptionCode = exceptionCode;
this.message = argMessage;
}
}
With some enumeration or serialization requirement you can add exceptionCode as well
public enum ExceptionCode {
SECTION_LOCKED(-0),
MAPPING_EXCEPTION(-110)
private final int value;
public int getValue() {
return this.value;
}
ExceptionCode(int value) {
this.value = value;
}
public static ExceptionCode findByName(String name) {
for (ExceptionCode v : values()) {
if (v.name().equals(name)) {
return v;
}
}
return null;
}
}
Then extend your customException from root GeneralException Containner
public class CustomException extends GeneralExceptionContainer {
public MappingException(ExceptionCode exceptionCode) {
super(exceptionCode.name(), exceptionCode.getValue());
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lunatic |
