简体   繁体   English

创建 Java 异常子类以呈现自定义消息

[英]Create Java Exception subclass to present custom message

I have security package in which the class files share the common Exception s:我有安全 package ,其中 class 文件共享常见的Exception s:

    catch (InvalidKeyException | NoSuchAlgorithmException e) {
            System.err.println("Key Exception: Invalid key is detected to sign or verify signature." + " \n");
        } catch (UnrecoverableKeyException e) {
            System.err.println("Key Exception: Faulty key can not be used to sign signature." + " \n");
        } catch (KeyStoreException e) {
            System.err.println("KeyStore Exception: key Store may be faulty." + " \n");
……………

I attempt the DSCoreException which can throw back custom descriptive messages based on the object's getLocalizedMessage() result, excluding the exception class name.我尝试了DSCoreException ,它可以根据对象的getLocalizedMessage()结果返回自定义描述性消息,不包括异常 class 名称。 The gist of the implementation is:实施的要点是:

catch (Exception e) {
  throw new DSCoreException(e);
} 
…………………..
class DSCoreException extends Exception {
  DSCoreException(Exception s) { 
        super(s.getLocalizedMessage());
        if (super.getLocalizedMessage().contains("Signature not available")) {
            System.err.println("Key Exception: Invalid key algorithm is used to sign signature." + " \n");
        }
}

It produces:它产生:

Key Exception: Invalid key algorithm is used to sign signature. 

Exception in thread "main" com.fc.security.DSCoreException: SHA512withDSA Signature not available
    at com.fc.security.TestException.main(TestException.java:91)

My expectation is:我的期望是:

Key Exception: Invalid key algorithm is used to sign signature. 

How can I display only my custom message?如何仅显示我的自定义消息? (There will be else-if following the if ) (在 if 之后会有else-if if

You have an Exception that prints messages.您有一个打印消息的异常。 That is not the job of an Exception.这不是异常的工作。

An Exception is supposed to provide enough information to describe the exception it's reporting.异常应该提供足够的信息来描述它报告的异常。 For example, it will typically have a message string.例如,它通常会有一个消息字符串。

If some code catches that Exception, it can (if it chooses) display the message string.如果某些代码捕获到该异常,它可以(如果选择)显示消息字符串。 But the Exception class never should.但是异常 class 永远不应该。

Your exception class should look like:您的异常 class 应该如下所示:

 class DSCoreException extends Exception {
      DSCoreException(String msg) {
          super(msg);
      }
      ... more needed here ...
 }

and then maybe you have an exception handler to replace particular exceptions by your own exception.然后也许你有一个异常处理程序来用你自己的异常替换特定的异常。

  try {
      do_something_here();
  } 
  catch (Exception ex) {  // NOTE really ought to be a narrower class
      if (ex.getLocalizedMessage().contains("Signature not available"))             
          ex = new DSCoreException("Key Exception: Invalid key algorithm is used to sign signature."); 
      throw ex;
  }

You catch the exception, examine it to see what it is, and optionally replace it with a better exception before re-throwing it.您捕获异常,检查它以查看它是什么,并在重新抛出它之前选择用更好的异常替换它。

A slightly different twist, depending on your overall needs:略有不同的转折,取决于您的整体需求:

  try {
      do_something_here();
  } 
  catch (Exception ex) {  // NOTE really ought to be a narrower class
      String msg = ex.getLocalizedMessage();
      if (msg.contains("Signature not available"))             
          msg = "Key Exception: Invalid key algorithm is used to sign signature."; 
      throw new DSCoreException(msg);
  }

That one always throws a DSCoreException but possibly replaces the message.那个总是抛出 DSCoreException 但可能会替换消息。 This converts all exceptions into 'your' class, which may have benefits to whoever is calling your code.这会将所有异常转换为“您的”class,这可能对调用您的代码的人有利。

The underlying lesson here is that an exception is a control-flow device, not just a thing that prints errors.这里的基本教训是异常是控制流设备,而不仅仅是打印错误的东西。 Even in the simple case where you intend to display the message, the exception is a way to get the error condition info to the code that is going to display it;即使在您打算显示消息的简单情况下,异常也是一种将错误条件信息获取到要显示它的代码的方法; the exception should not itself do the displaying.异常本身不应显示。

An objection raised, in a comment now deleted, was that the catcher of an exception could obtain a stack trace and thereby reveal information such as package names.在现已删除的评论中提出的反对意见是,异常捕获器可以获得堆栈跟踪,从而揭示诸如 package 名称之类的信息。 The OP apparently wants to prevent this, though I don't see why. OP 显然想阻止这种情况,但我不明白为什么。 That boils down to wanting an Exception to not behave like an Exception.这归结为希望异常的行为不像异常。 You can't control this in any reasonable way.你无法以任何合理的方式控制它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM