/** * Obtains a failure from a reason, throwable and message. * <p> * The message is produced using a template that contains zero to many "{}" placeholders. * Each placeholder is replaced by the next available argument. * If there are too few arguments, then the message will be left with placeholders. * If there are too many arguments, then the excess arguments are appended to the * end of the message. No attempt is made to format the arguments. * See {@link Messages#formatWithAttributes(String, Object...)} for more details. * * @param reason the reason * @param cause the cause * @param message a message explaining the failure, not empty, uses "{}" for inserting {@code messageArgs} * @param messageArgs the arguments for the message * @return the failure */ public static FailureItem of(FailureReason reason, Throwable cause, String message, Object... messageArgs) { ArgChecker.notNull(reason, "reason"); ArgChecker.notNull(cause, "cause"); Pair<String, Map<String, String>> msg = Messages.formatWithAttributes(message, messageArgs); String stackTrace = Throwables.getStackTraceAsString(cause).replace(System.lineSeparator(), "\n"); FailureItem base = new FailureItem(reason, msg.getFirst(), msg.getSecond(), stackTrace, cause.getClass()); String causeMessage = cause.getMessage(); if (!base.getAttributes().containsKey(EXCEPTION_MESSAGE_ATTRIBUTE) && !Strings.isNullOrEmpty(causeMessage)) { return base.withAttribute(EXCEPTION_MESSAGE_ATTRIBUTE, causeMessage); } return base; }
public void test_withAttribute() { FailureItem test = FailureItem.of(FailureReason.INVALID, "my {one} {two} failure", "big", "bad"); test = test.withAttribute("foo", "bar"); assertEquals(test.getAttributes(), ImmutableMap.of("one", "big", "two", "bad", "foo", "bar")); assertEquals(test.getReason(), FailureReason.INVALID); assertEquals(test.getMessage(), "my big bad failure"); assertFalse(test.getCauseType().isPresent()); assertFalse(test.getStackTrace().contains(".FailureItem.of(")); assertFalse(test.getStackTrace().contains(".Failure.of(")); assertTrue(test.getStackTrace().startsWith("com.opengamma.strata.collect.result.FailureItem: my big bad failure")); assertTrue(test.getStackTrace().contains(".test_withAttribute(")); assertEquals(test.toString(), "INVALID: my big bad failure"); }