Avoid printing expected exceptions inside HTTP tests (#11607)

This commit is contained in:
Radosław Waśko 2024-11-22 15:31:22 +01:00 committed by GitHub
parent 8891051475
commit dcabf6d0ae
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 28 additions and 1 deletions

View File

@ -9,6 +9,20 @@ import java.nio.charset.StandardCharsets;
public abstract class SimpleHttpHandler implements HttpHandler {
private final boolean logRequests = false;
/**
* A class that represents exceptions that are expected to be thrown (for testing crashing
* handlers). There is no need to log these.
*/
protected class ExpectedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public final boolean shouldBeRethrown;
public ExpectedException(boolean shouldBeRethrown) {
super("This exception is expected to be thrown.");
this.shouldBeRethrown = shouldBeRethrown;
}
}
@Override
public final void handle(HttpExchange exchange) throws IOException {
try {
@ -18,6 +32,11 @@ public abstract class SimpleHttpHandler implements HttpHandler {
}
doHandle(exchange);
} catch (ExpectedException e) {
exchange.close();
if (e.shouldBeRethrown) {
throw e;
}
} catch (IOException e) {
e.printStackTrace();
exchange.close();

View File

@ -51,7 +51,7 @@ public class CrashingTestHandler extends SimpleHttpHandler {
break;
} else {
requests += 1;
throw new RuntimeException("This handler crashes on purpose.");
throw new ExpectedException(false);
}
case STREAM:
@ -66,8 +66,16 @@ public class CrashingTestHandler extends SimpleHttpHandler {
}
} else {
requests += 1;
// This intentionally writes insufficient amount of data.
try (OutputStream os = exchange.getResponseBody()) {
os.write(responseData, 0, responseData.length / 2);
} catch (IOException e) {
if (e.getMessage().contains("insufficient bytes written to stream")) {
throw new ExpectedException(true);
} else {
// Unexpected exception - rethrow.
throw e;
}
}
}
} finally {