DEFENSIVE PROGRAMMING WITH KLOJANG CHECK

Custom Messages

If you want, you can provide a custom error message. Simply add the message as an extra argument to the is(...) or isNot(...) method. In fact, as explained in the chapters on common checks and error handling, you probably should do so if the check is a lambda or method reference (rather than a check from the CommonChecks class). Otherwise the user will be presented with an error message that is not very helpful. The message may contain message arguments whose values are subsequently specified in a varargs array. The first message argument can be referenced from within the message as ${0}, the second as ${1}, etc. For example:

    Check.that(word).is(keyIn(),
        dictionary, "Spelling error. Did you mean \"${0}\"?", "Pterodactylus");
    // Spelling error. Did you mean "Pterodactylus"?

The following message arguments are automatically available for use within the message pattern:

${test} The name of the check that was responsible for rejecting the value. For example: "lte" or "notNull"
${arg} The value that was rejected by the check
${tag} The tag or name assigned to the value (see Tagging Values). If no tag was provided, ${tag} will default to "argument"
${type} The simple class name of the value's type
${obj} The object of the relationship, in case the check took the form of a Relation or one of its sister interfaces. For example, for the instanceOf() check, ${obj} would be the class that the argument must be an instance of (Car.class in the examples that illustrated this check). For checks expressed through a Predicate or IntPredicate, ${obj} will be null.

Here is an example in which the message is dynamically generated, even though not a single message argument is provided within the is() call itself:

    Check.that("Peter", "firstName").is(substringOf(), "John Smith",
        "Invalid value for ${tag}: \"${arg}\". Not a substring of \"${obj}\".");
    // Invalid value for firstName: "Peter". Not a substring of "John Smith".