This product is not supported for your selected Datadog site. ().
Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Metadata

ID: java-best-practices/avoid-propagate-exception-info

Language: Java

Severity: Warning

Category: Best Practices

Description

This rule aims to discourage the direct propagation or usage of exception messages in the code. Exception messages can often contain sensitive or implementation-specific information that should not be exposed or relied upon for program logic. Relying on exception messages can lead to fragile code that breaks if the message text changes in future library or framework updates.

To comply with this rule, handle exceptions by using their types, custom error codes, or well-defined error objects instead of their message strings. For example, instead of e.getMessage(), consider catching specific exception subclasses or defining your own error classification. This approach leads to cleaner, more reliable error handling and protects sensitive information.

Example of compliant handling: catch (SpecificException ex) { log("Known error occurred"); } rather than inspecting ex.getMessage() contents.

Non-Compliant Code Examples

class Foo {
    public bar() {
        try {
            // something
        } catch (Exception e) {
            var message = someList.contains(e.getCause()) ? "known issue" : "unknown"
            System.out.println(message)
        }
    }
}
class Foo {
    public bar() {
        try {
            // something
        } catch (Exception e) {
            var message = someList.contains(e.getMessage()) ? e.getMessage() : "unknown"
            System.out.println(message)
        }
    }
}

Compliant Code Examples

class Foo {
    public bar() {
        try {
            // something
        } catch (Exception e) {
            System.out.println(message)
        }
    }
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains