首页 > Java > java教程 > 正文

项目 在消息详细信息中包含有关故障捕获的信息

DDD
发布: 2024-11-28 22:30:38
转载
964人浏览过

主要推荐
在异常消息中详细说明失败情况:

  • 包括导致失败的参数和字段的值。
  • 使用简洁且信息丰富的消息来帮助分析。
  • 示例:对于 indexoutofboundsexception,包括:
throw new indexoutofboundsexception("index: " + index + ", lower bound: " + lowerbound + ", upper bound: " + upperbound);

登录后复制

避免包含敏感数据

  • 切勿在详细消息中泄露密码、加密密钥或敏感信息,因为堆栈跟踪可以被多人查看。

优先考虑内容而不是可读性:

  • 详细信息应该针对开发者和工程师,协助故障分析。
  • 向最终用户发送的消息应该是单独且友好的,必要时进行本地化。

特定的构建者优势

  • 特定于异常的构造函数有助于捕获相关信息并自动生成消息。
  • 减少错误并确保捕获失败的一致性。
  • 理想构造函数的示例:
public class indexoutofboundsexception extends runtimeexception {
    private final int lowerbound;
    private final int upperbound;
    private final int index;

    public indexoutofboundsexception(int lowerbound, int upperbound, int index) {
        super("index: " + index + ", lower bound: " + lowerbound + ", upper bound: " + upperbound);
        this.lowerbound = lowerbound;
        this.upperbound = upperbound;
        this.index = index;
    }

    public int getlowerbound() {
        return lowerbound;
    }

    public int getupperbound() {
        return upperbound;
    }

    public int getindex() {
        return index;
    }
}

登录后复制

包含访问失败详细信息的方法

  • 对于受检查的异常,getter 可以方便恢复和分析。
  • 即使对于未检查的异常,也建议在适当的情况下提供 getter。

最佳实践

  • 将消息逻辑置于异常类中:
  • 避免在代码中的多个点重复详细的消息生成逻辑。
  • 集中式消息生成示例:
public class divisionbyzeroexception extends arithmeticexception {
    private final int numerator;

    public divisionbyzeroexception(int numerator) {
        super("attempted to divide " + numerator + " by zero.");
        this.numerator = numerator;
    }

    public int getnumerator() {
        return numerator;
    }
}

登录后复制

真实案例
indexoutofboundsexception 示例(java 9 ):

public indexoutofboundsexception(int index) {
    super("index out of range: " + index);
}

登录后复制

自定义类示例:

public class InvalidConfigurationException extends RuntimeException {
    private final String configKey;

    public InvalidConfigurationException(String configKey) {
        super("Invalid configuration for key: " + configKey);
        this.configKey = configKey;
    }

    public String getConfigKey() {
        return configKey;
    }
}

登录后复制

结论

  • 始终在异常消息中包含相关的失败信息,避免敏感数据。
  • 使用特定的构造函数和访问方法来捕获和记录关键信息。
  • 这些做法提高了可靠性,并使代码更易于调试和维护。

书中的示例:
项目 在消息详细信息中包含有关故障捕获的信息

以上就是项目 在消息详细信息中包含有关故障捕获的信息的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:dev.to网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号