Skip to content

Commit

Permalink
Fix issue apache#2363: Extract Throwable should be irrelevant to the …
Browse files Browse the repository at this point in the history
…count of patternAnalysis
  • Loading branch information
SeasonPanPan committed Mar 12, 2024
1 parent 222913d commit 60e5492
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
package org.apache.logging.log4j.message;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.math.BigDecimal;
import java.util.List;
Expand Down Expand Up @@ -159,6 +161,17 @@ void testSafeWithMutableParams() { // LOG4J2-763
assertThat(after).isEqualTo("Test message XYZ").as("Should not change after rendered once");
}

@Test
public void testException() {
final String testMsg = "Test message {}, exception is {}";
final ParameterizedMessage msg = new ParameterizedMessage(testMsg, "Apache", new NullPointerException());
final String result = msg.getFormattedMessage();
final String expected = "Test message Apache, exception is ";
assertThat(result).contains(expected);
final Throwable t = msg.getThrowable();
assertNotNull(t, "No Throwable");
}

static Stream<Object> testSerializable() {
@SuppressWarnings("EqualsHashCode")
class NonSerializable {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,19 +144,19 @@ public ParameterizedMessage(final String pattern, final Object[] args, final Thr
this.args = args;
this.pattern = pattern;
this.patternAnalysis = analyzePattern(pattern, args != null ? args.length : 0);
this.throwable = determineThrowable(throwable, this.args, patternAnalysis);
this.throwable = determineThrowable(throwable, this.args);
}

private static Throwable determineThrowable(
final Throwable throwable, final Object[] args, final MessagePatternAnalysis analysis) {
private static Throwable determineThrowable(final Throwable throwable, final Object[] args) {

// Short-circuit if an explicit `Throwable` is provided
if (throwable != null) {
return throwable;
}

// If the last `Throwable` argument is not consumed in the pattern, use that
if (args != null && args.length > analysis.placeholderCount) {
// Fix issue #2363: Extract Throwable should be irrelevant to the count of patternAnalysis
if (args != null && args.length > 0) {
Object lastArg = args[args.length - 1];
if (lastArg instanceof Throwable) {
return (Throwable) lastArg;
Expand Down

0 comments on commit 60e5492

Please sign in to comment.