E.GetMessage()和e.getLocalizedMessage()的异常方法显示包装



我正在为我的Java应用程序添加异常处理,并且不明白为什么在某些情况下, exception 方法返回的字符串 e.getMessage()e.getLocalizedMessage()包括我的自定义异常类。

这就是我配置的方式:

mycustomeXception:

package project.be.exception;
public class MyCustomException extends Exception{
 public MyCustomException() {
}
public MyCustomException(String arg0) {
    super(arg0);
}
public MyCustomException(Throwable arg0) {
    super(arg0);
}
public MyCustomException(String arg0, Throwable arg1) {
    super(arg0, arg1);
}
public MyCustomException(String arg0, Throwable arg1, boolean arg2, boolean arg3) {
    super(arg0, arg1, arg2, arg3);
}
}

myServiceCaller:

public class MyServiceCaller implements HISException DefaultRESTService<DefaultModel>{

    public DefaultResponse get(Service_Api service, Object caller, Object param) throws MyCustomException {
        try{
         ...
        } catch (Exception e){
           throw new MyCustomException ("Hello message exception");
        }
        }
}

mybussinessclass:

...
try{
 new MyServiceCaller().get(service, param1, param2);
} catch(MyCustomException e){
   System.out.println(e.getLocalizedMessage());
}
...

控制台输出:

project.be.exception: Hello message exception

我只想在没有以前的软件包的情况下打印消息。有任何建议吗?

edit1:

使用exception.getMessage((,输出是相同的,因此我丢弃可能的重复:e.getMessage((和e.getLocalizedMessage((之间的差异

解决方案:

正如艾萨克(Isaac(提到的那样,我正在将另一个抛出的异常包裹在另一个原因中,因此e.getMessage()e.getLocalizedMessage()显示了包裹。

在我的情况下,解决输出很容易调用e.getCause().getMessage(),而不是e.getMessage()e.getLocalizedMessage()

我建议您使用记录系统,而不是使用Java sysout:System.out.println(...)。使用日志记录系统,您可以定义日志的格式。

这是java.util.logging 的示例:

您可以定义自己的记录格式。这是Formatter的示例,它将仅显示任何例外的消息:

public class MyFormatter extends Formatter {
    public String format(LogRecord record) {
        StringBuilder builder = new StringBuilder();
        builder.append(formatMessage(record));
        builder.append("n");
        return builder.toString();
    }
}

然后您可以将其如下:

public class MyClass {
    // Your logger
    private static Logger logger ;
    // Static initialization block for the logger
    static {
        logger = Logger.getLogger("MyClass");
        try {
            ConsoleHandler handler = new ConsoleHandler();
            handler.setFormatter(new MyFormatter());
            logger.addHandler(handler);
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Failed to initialize Handler", e);
        }
    }
    //...
}

请注意,这是配置记录系统的正确方法。关键是要展示其工作原理。在真实应用程序中,您可以使用系统属性,配置文件等...

为了正确配置记录器,有几种解决方案。看看这个堆栈溢出问题:

  • 如何使Java记录输出出现在一行上?

我希望这对您有帮助。

最新更新