diff --git a/.docs/compatibility.md b/.docs/compatibility.md index 95f3640..7d4d253 100644 --- a/.docs/compatibility.md +++ b/.docs/compatibility.md @@ -2,7 +2,7 @@ ## Kotlin -The JSpecify annotations make `iban` a `String?` and a `when` over `MonetaException` exhaustive without an +The JSpecify annotations make `iban` a `String?` and a `when` over `MonetaApiException` exhaustive without an `else`, enforced from Kotlin 2.1. Kotlin 1.9, which Spring Boot 3 manages, only warns; add `-Xjspecify-annotations=strict` to the compiler options to make it an error. @@ -97,7 +97,7 @@ What to know before relying on it: - **The JDK client cannot do everything** an OkHttp or Apache stack can: a SOCKS proxy is skipped silently, Basic auth on an HTTPS proxy tunnel is off by default (`jdk.http.auth.tunneling.disabledSchemes`), NTLM is missing, and interceptors written for those stacks do not apply. There is no transport hook for them yet. -- **A failure inside a wrapper**: an `UncheckedIOException` becomes `MonetaException.NoAnswer`, anything else +- **A failure inside a wrapper**: an `UncheckedIOException` becomes `MonetaNoAnswerException`, anything else reaches you as it was thrown. - **`httpClient(…)`** still takes a client of your own, which you close, and which brings its own redirects, cookies and timeouts; `configureHttpClient` is refused beside it. diff --git a/.docs/usage.md b/.docs/usage.md index 0d7fc6f..8503679 100644 --- a/.docs/usage.md +++ b/.docs/usage.md @@ -118,21 +118,21 @@ holders.forEach { moneta.with(it.token).transactions().between(from, to).list() ## Failures -A sealed `MonetaException`, so a `switch` over it is exhaustive: +A sealed `MonetaApiException`, so a `switch` over it is exhaustive. Each subtype is a top-level class in `cz.insuit.moneta`: | Subtype | When | Do | |---------|------|----| -| `InvalidToken` | 401, 403 | get a new token | -| `RateLimited` | 429 | wait `retryAfter()` | -| `HttpError` | any other status | `body()` has MONETA's answer | -| `NoAnswer` | timeout, refused connection | retry | -| `InvalidResponse` | an unexpected body | report it | +| `MonetaInvalidTokenException` | 401, 403 | get a new token | +| `MonetaRateLimitedException` | 429 | wait `retryAfter()` | +| `MonetaHttpErrorException` | any other status | `body()` has MONETA's answer | +| `MonetaNoAnswerException` | timeout, refused connection | retry | +| `MonetaInvalidResponseException` | an unexpected body | report it | An interrupted thread throws `CancellationException` instead, interrupt flag kept. Each message names the request and, when MONETA sent one, its `X-Request-Id`, which MONETA's support asks for about one call: `GET /api/v4/vip/aisp/my/accounts?size=100&page=0 (X-Request-Id 7f3c…) answered 503`. Never the -token, nor the body; `body()` on `InvalidToken` and `HttpError` has the start of it. +token, nor the body; `body()` on `MonetaInvalidTokenException` and `MonetaHttpErrorException` has the start of it. ## Logging diff --git a/examples/cafe/src/main/java/example/cafe/BadRequests.java b/examples/cafe/src/main/java/example/cafe/BadRequests.java index ffd10d9..26ea72a 100644 --- a/examples/cafe/src/main/java/example/cafe/BadRequests.java +++ b/examples/cafe/src/main/java/example/cafe/BadRequests.java @@ -1,6 +1,6 @@ package example.cafe; -import cz.insuit.moneta.MonetaException; +import cz.insuit.moneta.MonetaApiException; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; @@ -12,9 +12,9 @@ class BadRequests { /** MONETA did not answer as asked; the café's own state is fine, so this is the bank's side, a 502. */ - @ExceptionHandler(MonetaException.class) + @ExceptionHandler(MonetaApiException.class) @ResponseStatus(HttpStatus.BAD_GATEWAY) - String monetaFailed(MonetaException e) { + String monetaFailed(MonetaApiException e) { return "MONETA: " + e.getMessage(); } diff --git a/examples/cafe/src/main/java/example/cafe/payment/PaymentRecorder.java b/examples/cafe/src/main/java/example/cafe/payment/PaymentRecorder.java index 2831499..6975c83 100644 --- a/examples/cafe/src/main/java/example/cafe/payment/PaymentRecorder.java +++ b/examples/cafe/src/main/java/example/cafe/payment/PaymentRecorder.java @@ -1,8 +1,8 @@ package example.cafe.payment; import cz.insuit.moneta.AccessToken; +import cz.insuit.moneta.MonetaApiException; import cz.insuit.moneta.MonetaClient; -import cz.insuit.moneta.MonetaException; import cz.insuit.moneta.Transaction; import example.cafe.CafeAccount; import example.cafe.bill.Bill; @@ -59,7 +59,7 @@ public class PaymentRecorder { void recordOnSchedule() { try { record(); - } catch (MonetaException e) { + } catch (MonetaApiException e) { // The next round tries again; a bank that is down is not the café's bug. log.warn("Could not read payments: {}", e.getMessage()); } diff --git a/modules/moneta-api-micronaut/README.md b/modules/moneta-api-micronaut/README.md index 306a813..52d8e26 100644 --- a/modules/moneta-api-micronaut/README.md +++ b/modules/moneta-api-micronaut/README.md @@ -165,18 +165,18 @@ An application that already bridges `java.util.logging` (Micronaut Starter's `ju Logback's `LevelChangePropagator`) needs nothing more. The module adds neither, since that choice is the application's. -Failures reach you as the client throws them, a `MonetaException`; the module catches nothing, retries nothing +Failures reach you as the client throws them, a `MonetaApiException`; the module catches nothing, retries nothing and logs nothing above DEBUG. Map them where the application decides what its callers see, an `ExceptionHandler` bean or an `@Error` route. MONETA refusing the token is not a 401 of your API: ```java @Singleton -class MonetaFailures implements ExceptionHandler> { +class MonetaFailures implements ExceptionHandler> { @Override - public HttpResponse handle(HttpRequest request, MonetaException failure) { + public HttpResponse handle(HttpRequest request, MonetaApiException failure) { return switch (failure) { - case MonetaException.RateLimited limited -> HttpResponse.status(HttpStatus.SERVICE_UNAVAILABLE); - case MonetaException.NoAnswer timeout -> HttpResponse.status(HttpStatus.GATEWAY_TIMEOUT); + case MonetaRateLimitedException limited -> HttpResponse.status(HttpStatus.SERVICE_UNAVAILABLE); + case MonetaNoAnswerException timeout -> HttpResponse.status(HttpStatus.GATEWAY_TIMEOUT); default -> HttpResponse.status(HttpStatus.BAD_GATEWAY); }; } diff --git a/modules/moneta-api-quarkus-deployment/src/test/java/cz/insuit/moneta/quarkus/deployment/MetricsTest.java b/modules/moneta-api-quarkus-deployment/src/test/java/cz/insuit/moneta/quarkus/deployment/MetricsTest.java index 6c40798..1099526 100644 --- a/modules/moneta-api-quarkus-deployment/src/test/java/cz/insuit/moneta/quarkus/deployment/MetricsTest.java +++ b/modules/moneta-api-quarkus-deployment/src/test/java/cz/insuit/moneta/quarkus/deployment/MetricsTest.java @@ -6,8 +6,8 @@ import cz.insuit.moneta.AccessToken; import cz.insuit.moneta.HttpClientDecorator; +import cz.insuit.moneta.MonetaApiException; import cz.insuit.moneta.MonetaClient; -import cz.insuit.moneta.MonetaException; import io.micrometer.core.instrument.simple.SimpleMeterRegistry; import io.micrometer.java11.instrument.binder.jdk.MicrometerHttpClient; import io.quarkus.test.QuarkusUnitTest; @@ -46,7 +46,7 @@ class MetricsTest { @Test void timesTheCallTaggedByItsTemplateNotTheAccount() { // FakeMoneta answers every path with accounts, so reading the balance fails; the call is timed all the same. - assertThrows(MonetaException.class, () -> moneta.balance(token, "acc-1")); + assertThrows(MonetaApiException.class, () -> moneta.balance(token, "acc-1")); var timer = meters.get("http.client.requests") .tag("uri", "/api/v4/vip/aisp/my/accounts/{accountId}/balance") diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/AccountHolder.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/AccountHolder.java index c8e4a5c..d0d2b76 100644 --- a/modules/moneta-api/src/main/java/cz/insuit/moneta/AccountHolder.java +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/AccountHolder.java @@ -46,7 +46,7 @@ public TransactionQuery transactions(String accountId) { * The only account's balance. * * @throws IllegalStateException when the token opens other than exactly one account - * @throws MonetaException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes + * @throws MonetaApiException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes * @throws CancellationException when the thread is interrupted; its interrupt flag stays set */ public Balance balance() { diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/Balance.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/Balance.java index b251139..f2882b8 100644 --- a/modules/moneta-api/src/main/java/cz/insuit/moneta/Balance.java +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/Balance.java @@ -26,7 +26,7 @@ private static Instant instant(String what, DateTimeValueJson date) { try { return date.instant(); } catch (DateTimeParseException e) { - throw new MonetaException.InvalidResponse(what + " sent the balance date " + date.dateTime(), e); + throw new MonetaInvalidResponseException(what + " sent the balance date " + date.dateTime(), e); } } @@ -35,6 +35,6 @@ private static BalanceJson ofType(String what, List balances, Balan .filter(balance -> code.name().equals(balance.type().codeOrProprietary().code())) .findFirst() - .orElseThrow(() -> new MonetaException.InvalidResponse(what + " sent no " + code + " balance", null)); + .orElseThrow(() -> new MonetaInvalidResponseException(what + " sent no " + code + " balance", null)); } } diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/CreditDebit.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/CreditDebit.java index a3be02a..84f114b 100644 --- a/modules/moneta-api/src/main/java/cz/insuit/moneta/CreditDebit.java +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/CreditDebit.java @@ -19,14 +19,14 @@ static CreditDebit of(String code) { return switch (code) { case "CRDT" -> CRDT; case "DBIT" -> DBIT; - default -> throw new MonetaException.InvalidResponse("unknown creditDebitIndicator '" + code + "'", null); + default -> throw new MonetaInvalidResponseException("unknown creditDebitIndicator '" + code + "'", null); }; } /** The amount with this direction as its sign. A negative one would be signed twice, so it is refused. */ Money signed(AmountJson amount) { if (amount.value().signum() < 0) { - throw new MonetaException.InvalidResponse("a negative amount beside creditDebitIndicator", null); + throw new MonetaInvalidResponseException("a negative amount beside creditDebitIndicator", null); } var unsigned = new Money(amount.value(), amount.currency()); return switch (this) { diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaApiException.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaApiException.java new file mode 100644 index 0000000..cc70232 --- /dev/null +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaApiException.java @@ -0,0 +1,23 @@ +package cz.insuit.moneta; + +import org.jspecify.annotations.Nullable; + +/** + * A call to MONETA that did not return what was asked for, one subtype per thing a caller does about it, so + * a {@code switch} over them is exhaustive. The message names the request and, when MONETA sent one, its + * {@code X-Request-Id}, which its support asks for; never the token, nor MONETA's response body. + * + *

The subtypes' constructors are public so a caller's own tests can throw them from a fake; the hierarchy + * stays closed. + */ +public abstract sealed class MonetaApiException extends RuntimeException + permits MonetaInvalidTokenException, + MonetaRateLimitedException, + MonetaHttpErrorException, + MonetaNoAnswerException, + MonetaInvalidResponseException { + + MonetaApiException(String message, @Nullable Throwable cause) { + super(message, cause); + } +} diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaClient.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaClient.java index e4b8ced..f85ac6a 100644 --- a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaClient.java +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaClient.java @@ -143,7 +143,7 @@ public void close() { /** * The accounts the token can see, all pages read. * - * @throws MonetaException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes + * @throws MonetaApiException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes * @throws CancellationException when the thread is interrupted; its interrupt flag stays set */ public List accounts(AccessToken token) { @@ -164,7 +164,7 @@ public List accounts(AccessToken token) { * @return null when the token does not see it: revoked for that account, or another holder's token * @throws IllegalArgumentException when the IBAN is blank or fails its check digits, a typo * @throws IllegalStateException when more than one account has that IBAN, as one per currency could - * @throws MonetaException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes + * @throws MonetaApiException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes * @throws CancellationException when the thread is interrupted; its interrupt flag stays set */ public @Nullable Account accountByIban(AccessToken token, String iban) { @@ -222,7 +222,7 @@ private static String normalisedIban(String iban) { * The account's booked and available balance, as of the instant MONETA computed it. * * @throws IllegalArgumentException when the account id is blank or a dot segment - * @throws MonetaException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes + * @throws MonetaApiException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes * @throws CancellationException when the thread is interrupted; its interrupt flag stays set */ public Balance balance(AccessToken token, String accountId) { @@ -236,8 +236,8 @@ public Balance balance(AccessToken token, String accountId) { * When the token stops working, so the merchant can be asked for a new one before it does. A sandbox token * expires after 20 minutes; a merchant's from Internet Banka lives longer, how long is up to MONETA. * - * @throws MonetaException.InvalidToken when the token has expired, or is not a MONETA API token (a 403) - * @throws MonetaException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes + * @throws MonetaInvalidTokenException when the token has expired, or is not a MONETA API token (a 403) + * @throws MonetaApiException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes * @throws CancellationException when the thread is interrupted; its interrupt flag stays set */ public Instant tokenExpiry(AccessToken token) { @@ -255,7 +255,7 @@ public Instant tokenExpiry(AccessToken token) { * * @throws IllegalArgumentException when {@code to} is before {@code from}, or the account id is blank or a * dot segment - * @throws MonetaException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes + * @throws MonetaApiException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes * @throws CancellationException when the thread is interrupted; its interrupt flag stays set */ public List incoming(AccessToken token, String accountId, LocalDate from, LocalDate to) { @@ -298,7 +298,7 @@ String onlyAccount(AccessToken token) { * * @throws IllegalArgumentException when {@code to} is before {@code from}, or the account id is blank or a * dot segment - * @throws MonetaException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes + * @throws MonetaApiException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes * @throws CancellationException when the thread is interrupted; its interrupt flag stays set */ public List transactions(AccessToken token, String accountId, LocalDate from, LocalDate to) { @@ -336,11 +336,11 @@ private List readAll( var items = body.items(); Integer number = body.pageNumber(); if (number != null && number != page) { - throw new MonetaException.InvalidResponse( + throw new MonetaInvalidResponseException( answer.call() + " asked for page " + page + " and got page " + number, null); } if (number == null && !items.isEmpty() && items.equals(previous)) { - throw new MonetaException.InvalidResponse( + throw new MonetaInvalidResponseException( answer.call() + " returned the same items for page " + page + " as for the one before," + " so the server likely ignores the page parameter", null); @@ -348,9 +348,9 @@ private List readAll( for (var node : items) { try { all.add(map.apply(node)); - } catch (MonetaException.InvalidResponse e) { + } catch (MonetaInvalidResponseException e) { var reference = node.path("entryReference").asString("?"); - throw new MonetaException.InvalidResponse( + throw new MonetaInvalidResponseException( answer.call() + ", item entryReference=" + reference + ": " + e.getMessage(), e); } } @@ -360,7 +360,7 @@ private List readAll( } previous = items; } - throw new MonetaException.InvalidResponse("GET /" + path + " did not end within " + MAX_PAGES + " pages", null); + throw new MonetaInvalidResponseException("GET /" + path + " did not end within " + MAX_PAGES + " pages", null); } /** @@ -387,9 +387,9 @@ private Answer get(AccessToken token, String what, String pathAndQuery, C } catch (IOException | UncheckedIOException e) { // A decorated client may report a failed exchange unchecked; it is the same missing answer. log(what, null, millisSince(started), null, e.toString()); - throw new MonetaException.NoAnswer(what + " did not get an answer", e); + throw new MonetaNoAnswerException(what + " did not get an answer", e); } catch (InterruptedException e) { - // Whoever owns the thread asked it to stop; that is not MONETA failing, so it is not a MonetaException + // Whoever owns the thread asked it to stop; that is not MONETA failing, so it is not a MonetaApiException // a retry would catch. Kotlin's coroutines read this type as cancellation. Thread.currentThread().interrupt(); var cancelled = new CancellationException(what + " was interrupted"); @@ -409,9 +409,9 @@ private Answer get(AccessToken token, String what, String pathAndQuery, C case 2 -> new Answer<>(parse(call, () -> JSON.readValue(response.body(), type)), call); default -> throw switch (status) { - case 401, 403 -> new MonetaException.InvalidToken(message, status, excerpt(response)); - case 429 -> new MonetaException.RateLimited(message, retryAfter(response)); - default -> new MonetaException.HttpError(message, status, excerpt(response), retryAfter(response)); + case 401, 403 -> new MonetaInvalidTokenException(message, status, excerpt(response)); + case 429 -> new MonetaRateLimitedException(message, retryAfter(response)); + default -> new MonetaHttpErrorException(message, status, excerpt(response), retryAfter(response)); }; }; } @@ -459,10 +459,10 @@ private static T parse(String what, Supplier<@Nullable T> read) { try { value = read.get(); } catch (RuntimeException e) { - throw new MonetaException.InvalidResponse(what + " returned a body this library cannot read", e); + throw new MonetaInvalidResponseException(what + " returned a body this library cannot read", e); } if (value == null) { - throw new MonetaException.InvalidResponse(what + " returned null", null); + throw new MonetaInvalidResponseException(what + " returned null", null); } return value; } @@ -562,7 +562,7 @@ public Builder configureHttpClient(Consumer configure) { * does not pass {@code close()} on leaks nothing, and a different client returned instead would bypass * both that and the library's settings. Whatever the decorator itself allocates is the caller's. Several * apply once per {@link #build()}, the first added innermost. An unchecked {@code UncheckedIOException} - * from the wrapper becomes {@link MonetaException.NoAnswer}; any other exception passes through as it is. + * from the wrapper becomes {@link MonetaNoAnswerException}; any other exception passes through as it is. */ public Builder decorateHttpClient(UnaryOperator decorator) { requireNonNull(decorator, "decorator"); diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaException.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaException.java deleted file mode 100644 index 96e93b8..0000000 --- a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaException.java +++ /dev/null @@ -1,102 +0,0 @@ -package cz.insuit.moneta; - -import java.time.Duration; -import org.jspecify.annotations.Nullable; - -/** - * A call to MONETA that did not return what was asked for, one subtype per thing a caller does about it, so - * a {@code switch} over them is exhaustive. The message names the request and, when MONETA sent one, its - * {@code X-Request-Id}, which its support asks for; never the token, nor MONETA's response body. - * - *

The subtypes' constructors are public so a caller's own tests can throw them from a fake; the hierarchy - * stays closed. - */ -public abstract sealed class MonetaException extends RuntimeException { - - MonetaException(String message, @Nullable Throwable cause) { - super(message, cause); - } - - /** The token was refused: revoked, expired, or without the rights the call needs. Retrying will not help. */ - public static final class InvalidToken extends MonetaException { - private final int status; - private final @Nullable String body; - - public InvalidToken(String message, int status, @Nullable String body) { - super(message, null); - this.status = status; - this.body = body; - } - - /** 401 or 403. */ - public int status() { - return status; - } - - /** The start of MONETA's answer, which may say why; kept out of the message so logging it is safe. */ - public @Nullable String body() { - return body; - } - } - - /** Too many calls. Retrying later will help. */ - public static final class RateLimited extends MonetaException { - private final @Nullable Duration retryAfter; - - public RateLimited(String message, @Nullable Duration retryAfter) { - super(message, null); - this.retryAfter = retryAfter; - } - - /** How long MONETA asked to wait, when it said so in seconds. */ - public @Nullable Duration retryAfter() { - return retryAfter; - } - } - - /** Any other status that is not a success. */ - public static final class HttpError extends MonetaException { - private final int status; - private final @Nullable String body; - private final @Nullable Duration retryAfter; - - public HttpError(String message, int status, @Nullable String body, @Nullable Duration retryAfter) { - super(message, null); - this.status = status; - this.body = body; - this.retryAfter = retryAfter; - } - - /** The HTTP status MONETA answered with. */ - public int status() { - return status; - } - - /** The first 2,000 characters of MONETA's answer, which usually say what was wrong with the request. */ - public @Nullable String body() { - return body; - } - - /** Set when MONETA said when to come back, as it may on a 503 during maintenance. */ - public @Nullable Duration retryAfter() { - return retryAfter; - } - } - - /** - * No answer came: a timeout or a refused connection. An interrupted thread is not one: that is a - * {@link java.util.concurrent.CancellationException}, so a retry does not repeat work someone cancelled. - */ - public static final class NoAnswer extends MonetaException { - public NoAnswer(String message, Throwable cause) { - super(message, cause); - } - } - - /** An answer came, but not in a shape this library can read: not JSON, or a required key missing. */ - public static final class InvalidResponse extends MonetaException { - public InvalidResponse(String message, @Nullable Throwable cause) { - super(message, cause); - } - } -} diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaHttpErrorException.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaHttpErrorException.java new file mode 100644 index 0000000..2db6c35 --- /dev/null +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaHttpErrorException.java @@ -0,0 +1,33 @@ +package cz.insuit.moneta; + +import java.time.Duration; +import org.jspecify.annotations.Nullable; + +/** Any other status that is not a success. */ +public final class MonetaHttpErrorException extends MonetaApiException { + private final int status; + private final @Nullable String body; + private final @Nullable Duration retryAfter; + + public MonetaHttpErrorException(String message, int status, @Nullable String body, @Nullable Duration retryAfter) { + super(message, null); + this.status = status; + this.body = body; + this.retryAfter = retryAfter; + } + + /** The HTTP status MONETA answered with. */ + public int status() { + return status; + } + + /** The first 2,000 characters of MONETA's answer, which usually say what was wrong with the request. */ + public @Nullable String body() { + return body; + } + + /** Set when MONETA said when to come back, as it may on a 503 during maintenance. */ + public @Nullable Duration retryAfter() { + return retryAfter; + } +} diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaInvalidResponseException.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaInvalidResponseException.java new file mode 100644 index 0000000..99c3f64 --- /dev/null +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaInvalidResponseException.java @@ -0,0 +1,10 @@ +package cz.insuit.moneta; + +import org.jspecify.annotations.Nullable; + +/** An answer came, but not in a shape this library can read: not JSON, or a required key missing. */ +public final class MonetaInvalidResponseException extends MonetaApiException { + public MonetaInvalidResponseException(String message, @Nullable Throwable cause) { + super(message, cause); + } +} diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaInvalidTokenException.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaInvalidTokenException.java new file mode 100644 index 0000000..014d4ee --- /dev/null +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaInvalidTokenException.java @@ -0,0 +1,25 @@ +package cz.insuit.moneta; + +import org.jspecify.annotations.Nullable; + +/** The token was refused: revoked, expired, or without the rights the call needs. Retrying will not help. */ +public final class MonetaInvalidTokenException extends MonetaApiException { + private final int status; + private final @Nullable String body; + + public MonetaInvalidTokenException(String message, int status, @Nullable String body) { + super(message, null); + this.status = status; + this.body = body; + } + + /** 401 or 403. */ + public int status() { + return status; + } + + /** The start of MONETA's answer, which may say why; kept out of the message so logging it is safe. */ + public @Nullable String body() { + return body; + } +} diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaNoAnswerException.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaNoAnswerException.java new file mode 100644 index 0000000..af929bc --- /dev/null +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaNoAnswerException.java @@ -0,0 +1,11 @@ +package cz.insuit.moneta; + +/** + * No answer came: a timeout or a refused connection. An interrupted thread is not one: that is a + * {@link java.util.concurrent.CancellationException}, so a retry does not repeat work someone cancelled. + */ +public final class MonetaNoAnswerException extends MonetaApiException { + public MonetaNoAnswerException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaRateLimitedException.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaRateLimitedException.java new file mode 100644 index 0000000..658378b --- /dev/null +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaRateLimitedException.java @@ -0,0 +1,19 @@ +package cz.insuit.moneta; + +import java.time.Duration; +import org.jspecify.annotations.Nullable; + +/** Too many calls. Retrying later will help. */ +public final class MonetaRateLimitedException extends MonetaApiException { + private final @Nullable Duration retryAfter; + + public MonetaRateLimitedException(String message, @Nullable Duration retryAfter) { + super(message, null); + this.retryAfter = retryAfter; + } + + /** How long MONETA asked to wait, when it said so in seconds. */ + public @Nullable Duration retryAfter() { + return retryAfter; + } +} diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/PageJson.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/PageJson.java index e567826..2d73997 100644 --- a/modules/moneta-api/src/main/java/cz/insuit/moneta/PageJson.java +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/PageJson.java @@ -9,7 +9,7 @@ * them by those names, so a key is written once, in its record, and the rest of the library reads typed fields. * The types end in {@code Json}, so they are not taken for the library's own model. Unknown keys are * ignored. A key the library relies on is checked in the compact constructor, so a missing one fails at - * binding, as {@link MonetaException.InvalidResponse}, and not as a null three calls later. + * binding, as {@link MonetaInvalidResponseException}, and not as a null three calls later. * *

{@code PageJson} itself is one page of a list. Its items stay JSON trees, so each one can be kept verbatim * besides being bound. diff --git a/modules/moneta-api/src/main/java/cz/insuit/moneta/TransactionQuery.java b/modules/moneta-api/src/main/java/cz/insuit/moneta/TransactionQuery.java index 82417a7..05c178a 100644 --- a/modules/moneta-api/src/main/java/cz/insuit/moneta/TransactionQuery.java +++ b/modules/moneta-api/src/main/java/cz/insuit/moneta/TransactionQuery.java @@ -82,7 +82,7 @@ public TransactionQuery pending() { * token opens other than exactly one * @throws IllegalArgumentException when {@code to} is before {@code from}, or the account id is blank or a * dot segment - * @throws MonetaException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes + * @throws MonetaApiException when MONETA refuses, fails or answers in an unexpected shape; see its subtypes * @throws CancellationException when the thread is interrupted; its interrupt flag stays set */ public List list() { diff --git a/modules/moneta-api/src/test/java/cz/insuit/moneta/MonetaClientTest.java b/modules/moneta-api/src/test/java/cz/insuit/moneta/MonetaClientTest.java index aead004..b6f9403 100644 --- a/modules/moneta-api/src/test/java/cz/insuit/moneta/MonetaClientTest.java +++ b/modules/moneta-api/src/test/java/cz/insuit/moneta/MonetaClientTest.java @@ -205,7 +205,7 @@ void aServerThatIgnoresThePageIsRefusedRatherThanReadThreeTimes() { var alwaysPageZero = """ {"accounts": [{"id": "a", "currency": "CZK"}], "pageNumber": 0, "pageCount": 3}"""; answer(ACCOUNTS, 200, alwaysPageZero); - assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN)); + assertThrows(MonetaInvalidResponseException.class, () -> client.accounts(TOKEN)); } @Test @@ -214,13 +214,13 @@ void aServerThatCountsPagesFromOneIsRefused() { var firstPageIsOne = """ {"accounts": [{"id": "a", "currency": "CZK"}], "pageNumber": 1, "pageCount": 2}"""; answer(ACCOUNTS, 200, firstPageIsOne); - assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN)); + assertThrows(MonetaInvalidResponseException.class, () -> client.accounts(TOKEN)); } @Test void theSamePageOverAndOverWithoutPageNumbersIsRefused() { answer(ACCOUNTS, 200, ONE_ACCOUNT); - assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN)); + assertThrows(MonetaInvalidResponseException.class, () -> client.accounts(TOKEN)); assertEquals(2, requests.size()); } } @@ -403,7 +403,7 @@ void readsWhenTheTokenExpires() { void aTokenAnswerWithoutAnExpiryIsRefused() { answer(TOKEN_INTROSPECT, 200, "{}"); - assertThrows(MonetaException.InvalidResponse.class, () -> client.tokenExpiry(TOKEN)); + assertThrows(MonetaInvalidResponseException.class, () -> client.tokenExpiry(TOKEN)); } @Test @@ -411,7 +411,7 @@ void aTokenThatIsNotMonetasIsInvalidToken() { answer(TOKEN_INTROSPECT, 403, """ {"errors": [{"error": "FORBIDDEN", "message": "This is not a Moneta API token."}]}"""); - assertThrows(MonetaException.InvalidToken.class, () -> client.tokenExpiry(TOKEN)); + assertThrows(MonetaInvalidTokenException.class, () -> client.tokenExpiry(TOKEN)); } @Test @@ -444,7 +444,7 @@ void aBalanceWithAnUnreadableDateIsRefused() { ]}"""; answer(BALANCE, 200, garbled); - assertThrows(MonetaException.InvalidResponse.class, () -> client.balance(TOKEN, "acc-1")); + assertThrows(MonetaInvalidResponseException.class, () -> client.balance(TOKEN, "acc-1")); } @Test @@ -460,7 +460,7 @@ void aBalanceWithoutTheAvailableOneIsRefused() { respond(exchange, 200, bookedOnly); }); - var refused = assertThrows(MonetaException.InvalidResponse.class, () -> client.balance(TOKEN, "acc-1")); + var refused = assertThrows(MonetaInvalidResponseException.class, () -> client.balance(TOKEN, "acc-1")); assertTrue(String.valueOf(refused.getMessage()).contains("CLAV"), refused.getMessage()); assertTrue(String.valueOf(refused.getMessage()).contains("X-Request-Id req-7"), refused.getMessage()); } @@ -742,31 +742,31 @@ void anUnknownStatusIsKeptAsOther() { @Test void anUnknownDirectionIsRefusedRatherThanGuessed() { answer(TRANSACTIONS, 200, movement("BOOK", "XXXX")); - assertThrows(MonetaException.InvalidResponse.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); + assertThrows(MonetaInvalidResponseException.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); } @Test void aNegativeAmountBesideADebitIsRefusedRatherThanSignedTwice() { answer(TRANSACTIONS, 200, movement("BOOK", "DBIT", "-100.00", "CZK")); - assertThrows(MonetaException.InvalidResponse.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); + assertThrows(MonetaInvalidResponseException.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); } } - /** A 200 whose body is not the expected shape is always an InvalidResponse. */ + /** A 200 whose body is not the expected shape is always a MonetaInvalidResponseException. */ @Nested class UnreadableAnswers { @Test void aBodyOfTheWrongShapeIsAnInvalidResponse() { answer(ACCOUNTS, 200, "gateway"); - assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN)); + assertThrows(MonetaInvalidResponseException.class, () -> client.accounts(TOKEN)); server.removeContext(ACCOUNTS); // language=JSON var noId = """ {"accounts": [{"currency": "CZK"}]}"""; answer(ACCOUNTS, 200, noId); - assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN)); + assertThrows(MonetaInvalidResponseException.class, () -> client.accounts(TOKEN)); } static Stream wrongAccountsBodies() { @@ -788,7 +788,7 @@ static Stream wrongAccountsBodies() { @MethodSource("wrongAccountsBodies") void anyAccountsBodyOfTheWrongShapeIsAnInvalidResponse(String body) { answer(ACCOUNTS, 200, body); - assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN)); + assertThrows(MonetaInvalidResponseException.class, () -> client.accounts(TOKEN)); } static Stream wrongTransactionsBodies() { @@ -799,7 +799,7 @@ static Stream wrongTransactionsBodies() { @MethodSource("wrongTransactionsBodies") void anyTransactionsBodyOfTheWrongShapeIsAnInvalidResponse(String body) { answer(TRANSACTIONS, 200, body); - assertThrows(MonetaException.InvalidResponse.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); + assertThrows(MonetaInvalidResponseException.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); } @ParameterizedTest @@ -809,7 +809,7 @@ void aMovementWithoutARequiredKeyIsAnInvalidResponse(String key) { ((ObjectNode) page.get("transactions").get(0)).remove(key); answer(TRANSACTIONS, 200, page.toString()); - assertThrows(MonetaException.InvalidResponse.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); + assertThrows(MonetaInvalidResponseException.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); } @Test @@ -818,7 +818,7 @@ void anAccountWithoutACurrencyIsAnInvalidResponse() { var noCurrency = """ {"accounts": [{"id": "a"}], "pageCount": 1}"""; answer(ACCOUNTS, 200, noCurrency); - assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN)); + assertThrows(MonetaInvalidResponseException.class, () -> client.accounts(TOKEN)); } @Test @@ -830,7 +830,7 @@ void aBrokenItemNamesTheRequestThePageAndTheMovement() { }); var failed = assertThrows( - MonetaException.InvalidResponse.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); + MonetaInvalidResponseException.class, () -> client.transactions(TOKEN, "acc-1", FROM, TO)); var message = Objects.requireNonNull(failed.getMessage()); assertTrue(message.contains("page=1"), message); assertTrue(message.contains("X-Request-Id req-1"), message); @@ -847,7 +847,7 @@ class Failures { @ValueSource(ints = {401, 403}) void aRefusedTokenIsInvalidToken(int status) { answer(ACCOUNTS, status, "{}"); - var refused = assertThrows(MonetaException.InvalidToken.class, () -> client.accounts(TOKEN)); + var refused = assertThrows(MonetaInvalidTokenException.class, () -> client.accounts(TOKEN)); assertEquals(status, refused.status()); assertFalse(Objects.requireNonNull(refused.getMessage()).contains(TOKEN.value())); } @@ -858,7 +858,7 @@ void throttlingSaysHowLongToWait() { exchange.getResponseHeaders().add("Retry-After", "30"); respond(exchange, 429, "{}"); }); - var throttled = assertThrows(MonetaException.RateLimited.class, () -> client.accounts(TOKEN)); + var throttled = assertThrows(MonetaRateLimitedException.class, () -> client.accounts(TOKEN)); assertEquals(Duration.ofSeconds(30), throttled.retryAfter()); } @@ -869,14 +869,14 @@ void aRetryAfterThatIsNotSecondsIsStillRateLimited(String retryAfter) { exchange.getResponseHeaders().add("Retry-After", retryAfter); respond(exchange, 429, "{}"); }); - var throttled = assertThrows(MonetaException.RateLimited.class, () -> client.accounts(TOKEN)); + var throttled = assertThrows(MonetaRateLimitedException.class, () -> client.accounts(TOKEN)); assertNull(throttled.retryAfter()); } @Test void reportsAnyOtherFailureWithItsStatus() { answer(ACCOUNTS, 503, "{}"); - var failed = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN)); + var failed = assertThrows(MonetaHttpErrorException.class, () -> client.accounts(TOKEN)); assertEquals(503, failed.status()); // MONETA sent no X-Request-Id here, so the message has no empty or "null" one. assertFalse(String.valueOf(failed.getMessage()).contains("X-Request-Id"), failed.getMessage()); @@ -888,13 +888,13 @@ void anErrorKeepsTheStartOfItsBodyOutOfTheMessage() { var error = """ {"error": "unknown parameter size"}"""; answer(ACCOUNTS, 400, error); - var failed = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN)); + var failed = assertThrows(MonetaHttpErrorException.class, () -> client.accounts(TOKEN)); assertEquals(error, failed.body()); assertFalse(Objects.requireNonNull(failed.getMessage()).contains("unknown parameter")); server.removeContext(ACCOUNTS); answer(ACCOUNTS, 400, "x".repeat(5_000)); - var long_ = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN)); + var long_ = assertThrows(MonetaHttpErrorException.class, () -> client.accounts(TOKEN)); assertEquals(2_000, Objects.requireNonNull(long_.body()).length()); } @@ -904,7 +904,7 @@ void aMaintenanceAnswerSaysWhenToComeBack() { exchange.getResponseHeaders().add("Retry-After", "120"); respond(exchange, 503, "{}"); }); - var failed = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN)); + var failed = assertThrows(MonetaHttpErrorException.class, () -> client.accounts(TOKEN)); assertEquals(Duration.ofMinutes(2), failed.retryAfter()); } @@ -914,7 +914,7 @@ void aFailureNamesTheRequestIdMonetasSupportAsksFor() { exchange.getResponseHeaders().add("X-Request-Id", "req-42"); respond(exchange, 503, "{}"); }); - var failed = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN)); + var failed = assertThrows(MonetaHttpErrorException.class, () -> client.accounts(TOKEN)); assertTrue(String.valueOf(failed.getMessage()).contains("X-Request-Id req-42"), failed.getMessage()); server.removeContext(ACCOUNTS); @@ -922,7 +922,7 @@ void aFailureNamesTheRequestIdMonetasSupportAsksFor() { exchange.getResponseHeaders().add("X-Request-Id", "req-43"); respond(exchange, 200, "not json"); }); - var unreadable = assertThrows(MonetaException.InvalidResponse.class, () -> client.accounts(TOKEN)); + var unreadable = assertThrows(MonetaInvalidResponseException.class, () -> client.accounts(TOKEN)); assertTrue( String.valueOf(unreadable.getMessage()).contains("X-Request-Id req-43"), unreadable.getMessage()); } @@ -934,7 +934,7 @@ void aRequestIdThatIsNotShortPrintableAsciiStaysOutOfTheMessage() { exchange.getResponseHeaders().add("X-Request-Id", requestId); respond(exchange, 503, "{}"); }); - var failed = assertThrows(MonetaException.HttpError.class, () -> client.accounts(TOKEN)); + var failed = assertThrows(MonetaHttpErrorException.class, () -> client.accounts(TOKEN)); assertFalse(String.valueOf(failed.getMessage()).contains("X-Request-Id"), failed.getMessage()); server.removeContext(ACCOUNTS); } @@ -983,8 +983,8 @@ public void close() {} @Test void aServerThatIsGoneIsNoAnswer() { server.stop(0); - var failed = assertThrows(MonetaException.class, () -> client.accounts(TOKEN)); - assertInstanceOf(MonetaException.NoAnswer.class, failed); + var failed = assertThrows(MonetaApiException.class, () -> client.accounts(TOKEN)); + assertInstanceOf(MonetaNoAnswerException.class, failed); } @Test @@ -999,7 +999,7 @@ void givesUpAfterTheRequestTimeout() { .build(); long start = System.nanoTime(); - var failed = assertThrows(MonetaException.NoAnswer.class, () -> impatient.accounts(TOKEN)); + var failed = assertThrows(MonetaNoAnswerException.class, () -> impatient.accounts(TOKEN)); assertInstanceOf(HttpTimeoutException.class, failed.getCause()); assertTrue(Duration.ofNanos(System.nanoTime() - start).compareTo(Duration.ofMillis(900)) < 0); } @@ -1074,7 +1074,7 @@ void closesOnlyTheHttpClientItMade() { answer(ACCOUNTS, 200, fixture("accounts.json")); var own = MonetaClient.builder().baseUri(base).build(); own.close(); - assertThrows(MonetaException.NoAnswer.class, () -> own.accounts(TOKEN)); + assertThrows(MonetaNoAnswerException.class, () -> own.accounts(TOKEN)); var http = HttpClient.newHttpClient(); MonetaClient.builder().baseUri(base).httpClient(http).build().close(); @@ -1136,7 +1136,7 @@ void closesTheClientItBuiltBehindAWrapperThatDoesNotPassCloseOn() { decorated.close(); - assertThrows(MonetaException.NoAnswer.class, () -> decorated.accounts(TOKEN)); + assertThrows(MonetaNoAnswerException.class, () -> decorated.accounts(TOKEN)); } @Test @@ -1198,7 +1198,7 @@ void anUncheckedIoFailureFromAWrapperIsNoAnswer() { })) .build(); - assertThrows(MonetaException.NoAnswer.class, () -> failing.accounts(TOKEN)); + assertThrows(MonetaNoAnswerException.class, () -> failing.accounts(TOKEN)); } @Test diff --git a/modules/moneta-api/src/test/java/example/CallerTest.java b/modules/moneta-api/src/test/java/example/CallerTest.java index 73fb3c3..477ad9e 100644 --- a/modules/moneta-api/src/test/java/example/CallerTest.java +++ b/modules/moneta-api/src/test/java/example/CallerTest.java @@ -2,7 +2,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -import cz.insuit.moneta.MonetaException; +import cz.insuit.moneta.MonetaApiException; +import cz.insuit.moneta.MonetaHttpErrorException; +import cz.insuit.moneta.MonetaInvalidResponseException; +import cz.insuit.moneta.MonetaInvalidTokenException; +import cz.insuit.moneta.MonetaNoAnswerException; +import cz.insuit.moneta.MonetaRateLimitedException; import java.io.IOException; import java.time.Duration; import org.junit.jupiter.api.Test; @@ -12,12 +17,12 @@ class CallerTest { @Test void aCallersFakeCanThrowEveryFailure() { - var failures = new MonetaException[] { - new MonetaException.InvalidToken("refused", 401, null), - new MonetaException.RateLimited("slow", Duration.ofSeconds(5)), - new MonetaException.HttpError("down", 503, null, null), - new MonetaException.NoAnswer("gone", new IOException("reset")), - new MonetaException.InvalidResponse("odd", null) + var failures = new MonetaApiException[] { + new MonetaInvalidTokenException("refused", 401, null), + new MonetaRateLimitedException("slow", Duration.ofSeconds(5)), + new MonetaHttpErrorException("down", 503, null, null), + new MonetaNoAnswerException("gone", new IOException("reset")), + new MonetaInvalidResponseException("odd", null) }; assertEquals(5, failures.length); } diff --git a/testing/README.md b/testing/README.md index 679be9e..3033335 100644 --- a/testing/README.md +++ b/testing/README.md @@ -15,7 +15,7 @@ break it unnoticed. `make build` runs them with the library's own tests, which s | `micronaut/5.2.5` | the same jar, compiled for Micronaut 4, loads and binds on Micronaut 5; runs on JDK 25 whatever `-PtestsJdk` says | | `quarkus/3.33.4` | the Quarkus extension on the Quarkus it is compiled against, with the platform BOM a caller imports and no Micrometer | | `quarkus/3.40.1` | the same jar on the current LTS, with `quarkus-micrometer` but not `micrometer-java11`, so the extension's metrics stay off without a missing class; `make native-test` also builds it native, with the Jackson fix from [compatibility](../.docs/compatibility.md#quarkus), and runs it on Linux | -| `kotlin` | a `when` over `MonetaException` needs no `else`, and a nullable component is nullable in Kotlin | +| `kotlin` | a `when` over `MonetaApiException` needs no `else`, and a nullable component is nullable in Kotlin | | `native` | the client's metadata is enough for a native image: built by `make native-test`, not `make build`, it prints the same as on the JVM | Each Spring Boot version is a folder whose `build.gradle.kts` imports its BOM, plus whatever only that version diff --git a/testing/kotlin/src/test/kotlin/example/kotlin/KotlinCallerTest.kt b/testing/kotlin/src/test/kotlin/example/kotlin/KotlinCallerTest.kt index 2aab9db..b345d28 100644 --- a/testing/kotlin/src/test/kotlin/example/kotlin/KotlinCallerTest.kt +++ b/testing/kotlin/src/test/kotlin/example/kotlin/KotlinCallerTest.kt @@ -1,6 +1,11 @@ package example.kotlin -import cz.insuit.moneta.MonetaException +import cz.insuit.moneta.MonetaApiException +import cz.insuit.moneta.MonetaHttpErrorException +import cz.insuit.moneta.MonetaInvalidResponseException +import cz.insuit.moneta.MonetaInvalidTokenException +import cz.insuit.moneta.MonetaNoAnswerException +import cz.insuit.moneta.MonetaRateLimitedException import org.jetbrains.kotlin.cli.common.arguments.K2JVMCompilerArguments import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSourceLocation @@ -17,17 +22,17 @@ import kotlin.io.path.writeText class KotlinCallerTest { @Test fun aWhenOverEveryFailureNeedsNoElse() { - // Compiles only while Kotlin sees MonetaException as sealed. - fun action(failure: MonetaException): String = + // Compiles only while Kotlin sees MonetaApiException as sealed. + fun action(failure: MonetaApiException): String = when (failure) { - is MonetaException.InvalidToken -> "ask for a new token" - is MonetaException.RateLimited -> "wait" - is MonetaException.HttpError -> "report" - is MonetaException.NoAnswer -> "retry" - is MonetaException.InvalidResponse -> "report" + is MonetaInvalidTokenException -> "ask for a new token" + is MonetaRateLimitedException -> "wait" + is MonetaHttpErrorException -> "report" + is MonetaNoAnswerException -> "retry" + is MonetaInvalidResponseException -> "report" } - assertEquals("wait", action(MonetaException.RateLimited("slow", null))) + assertEquals("wait", action(MonetaRateLimitedException("slow", null))) } @Test diff --git a/testing/play/shared/src/test/java/example/play/MonetaInPlayTest.java b/testing/play/shared/src/test/java/example/play/MonetaInPlayTest.java index 9bec6a8..e748e0b 100644 --- a/testing/play/shared/src/test/java/example/play/MonetaInPlayTest.java +++ b/testing/play/shared/src/test/java/example/play/MonetaInPlayTest.java @@ -13,7 +13,7 @@ import com.sun.net.httpserver.HttpServer; import cz.insuit.moneta.AccessToken; import cz.insuit.moneta.MonetaClient; -import cz.insuit.moneta.MonetaException; +import cz.insuit.moneta.MonetaNoAnswerException; import cz.insuit.moneta.Money; import java.io.IOException; import java.math.BigDecimal; @@ -144,7 +144,7 @@ void stoppingTheApplicationClosesTheClient() throws Exception { // The JDK client refuses to send once closed; the library reports that as no answer. assertThrows( - MonetaException.NoAnswer.class, + MonetaNoAnswerException.class, () -> moneta.transactions( new AccessToken("t"), "acc-1", LocalDate.of(2026, 8, 1), LocalDate.of(2026, 8, 31))); }