Part 14 / Topic 7 of 7
Putting it together: route webhook-style events with a pattern-matching switch
Real-world example: a payment-gateway-style webhook handler — the shape a UPI or card payment provider's callback takes once its JSON has already been deserialized into typed events. WebhookEvent is sealed over four record types; route is one exhaustive, guarded, deconstructing switch, no default needed; routeRaw adds the case null / default safety net one layer up, for a payload that never became a WebhookEvent at all (section 3's Object pattern, reused for real).
sealed interface WebhookEvent permits PaymentSuccess, PaymentFailed, RefundInitiated, OrderStatusUpdate {}
record PaymentSuccess(String orderId, long amountPaise, String upiRef) implements WebhookEvent {}
record PaymentFailed(String orderId, String reasonCode) implements WebhookEvent {}
record RefundInitiated(String orderId, long amountPaise) implements WebhookEvent {}
record OrderStatusUpdate(String orderId, String status) implements WebhookEvent {}
static String route(WebhookEvent event) {
return switch (event) {
case PaymentSuccess(var orderId, var amountPaise, var upiRef) when amountPaise >= 100_000_00L ->
"ALERT " + orderId + ": high-value payment (Rs " + (amountPaise / 100) + "), flagged for manual review, ref " + upiRef;
case PaymentSuccess(var orderId, var amountPaise, var upiRef) ->
"LEDGER " + orderId + ": payment confirmed, Rs " + (amountPaise / 100) + ", ref " + upiRef;
// PaymentFailed, RefundInitiated, OrderStatusUpdate: same shape, one guarded case + one fallback each
};
}
$ javac WebhookEventRouter.java
$ java WebhookEventRouter
-- routing typed webhook events --
LEDGER ORD-7001: payment confirmed, Rs 1499, ref UPI2026112012345
ALERT ORD-7002: high-value payment (Rs 150000), flagged for manual review, ref UPI2026112067890
NOTIFY ORD-7003: payment failed (insufficient funds), prompt customer to retry
SUPPORT ORD-7004: payment failed (BANK_TIMEOUT), escalate to support queue
LEDGER ORD-7001: refund of Rs 1499 initiated
TRACKING ORD-7005: status changed to SHIPPED
NOTIFY ORD-7005: delivered, request a rating
-- routing raw payloads, including a malformed one --
LEDGER ORD-7001: payment confirmed, Rs 1499, ref UPI2026112012345
DROP: empty webhook payload, nothing to route
DROP: unrecognized payload type String
SUPPORT ORD-7004: payment failed (BANK_TIMEOUT), escalate to support queue
Two things worth noticing: the ₹1,50,000 payment is caught by the guarded case, checked before the plain PaymentSuccess fallback, because switch guards are checked top to bottom like any other switch; and a null or stray String payload never reaches route at all — routeRaw's own case null/default stops it one layer up, exactly where section 3 said that safety net belongs.
Full program: examples/WebhookEventRouter.java.
Done here? The practice set for Part 14 — including the solutions — is on the part page.