i needed some help understanding the best practice for this scenario.
I have a custom exception class I created that has 3 child classes.I was overriding the message to fit my need . Now the child classes also need to have a custom message. Can I somehow find a way to leverage using the parent class but with a different format ?
Parent Exception Class
public class customException extends RuntimeException {
String myFormat = " Custom Exception message here , %s, %s";
private String A;
public customException(String A, String message){
this.A= A;
super(message);
}
@Override
public String getMessage() {
return String.Format(myFormat, A, super.getMessage());
}
Child Exception class example
public class childException extends customException {
String myFormat = " ChildException message here , %s, %s";
public customException(String A, String message){
super(A, message);
}
@Override
public String getMessage() {
return super.getMessage(); // find a way to format using the ChildClass myFormat?
}
EDIT :
The workaround i had currently looked something like this.
Child Exception class example
public class childException extends customException {
String myFormat = " ChildException message here , %s, %s";
private String A;
public customException(String A, String message){
super(message); // have another constructor in the Parent exception class
this.A=A;
}
@Override
public String getMessage() {
return String.Format(myFormat, A, super.getMessage());
}
And to avoid the super.getMessage() above, to print the format of the parent exception as well I was checking on the getMessage() method in the super class to see if the class is an instance of the child class. Not a suitable solution.
@Override
public String getMessage() {
if( this instanceOf childException)
return super.getMessage();
else
return String.Format(myFormat, A, super.getMessage());
}
Why dont you change the return super.getMessage() line in childException class.
Instead of:
@Override
public String getMessage() {
return super.getMessage(); // find a way to format using the ChildClass myFormat?
}
Try:
@Override
public String getMessage() {
this.myFormat = this.myFormat.append("hello");
return this.myFormat; // find a way to format using the ChildClass myFormat?
}