java - 格式化自定义错误消息的基本问题

标签 java error-handling custom-error-handling

我需要一些帮助来了解这种情况下的最佳实践。
我创建了一个自定义的异常类,该异常类具有3个子类。我正在覆盖消息以适合我的需要。
现在,子类也需要具有自定义消息。我能以某种方式找到一种利用父类但格式不同的方法吗?
家长异常(exception)类别

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());
}
子异常类示例
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? 
    }
编辑:
解决方法我目前看起来像这样。
子异常类示例
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()); 
    }
为了避免上面的super.getMessage(),也要打印父异常的格式,因此我检查了父类(super class)中的getMessage()方法,以查看该类是否为子类的实例。不适合的解决方案。
@Override
public String getMessage() {
if( this instanceOf childException)
return super.getMessage();
else
return String.Format(myFormat, A, super.getMessage());
}

最佳答案

为什么不更改childException类中的return super.getMessage()行。
代替:

@Override
public String getMessage() {
    return   super.getMessage();    // find a way to format using the ChildClass myFormat? 
}
尝试:
@Override
public String getMessage() {
  this.myFormat = this.myFormat.append("hello");
  return this.myFormat; // find a way to format using the ChildClass myFormat? 
}

关于java - 格式化自定义错误消息的基本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65684499/

相关文章:

java - Java 如何防止尚未分配的实例被垃圾回收?

c# - IErrorHandler WCF配置为返回文本/纯文本

php - 正确的set_error_handler()函数引用链接

javascript - 检测JavaScript使客户端崩溃

httpwebrequest - 有没有办法改变 400/500 状态码的 HttpWebRequest 行为?

java - Libgdx Terraria 克隆世界创建时间太长

java - 如何测量算法的时间

java - 通过套接字接收文件,TCP 连接卡住

ios - 如何使 cordova ios 应用程序崩溃

php - 从 error_handler 访问变量