Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .docs/compatibility.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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.
Expand Down
14 changes: 7 additions & 7 deletions .docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
6 changes: 3 additions & 3 deletions examples/cafe/src/main/java/example/cafe/BadRequests.java
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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();
}

Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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());
}
Expand Down
10 changes: 5 additions & 5 deletions modules/moneta-api-micronaut/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<MonetaException, HttpResponse<?>> {
class MonetaFailures implements ExceptionHandler<MonetaApiException, HttpResponse<?>> {
@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);
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand All @@ -35,6 +35,6 @@ private static BalanceJson ofType(String what, List<BalanceJson> 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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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);
}
}
40 changes: 20 additions & 20 deletions modules/moneta-api/src/main/java/cz/insuit/moneta/MonetaClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -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<Account> accounts(AccessToken token) {
Expand All @@ -164,7 +164,7 @@ public List<Account> 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) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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) {
Expand All @@ -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<Transaction> incoming(AccessToken token, String accountId, LocalDate from, LocalDate to) {
Expand Down Expand Up @@ -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<Transaction> transactions(AccessToken token, String accountId, LocalDate from, LocalDate to) {
Expand Down Expand Up @@ -336,21 +336,21 @@ private <T> List<T> 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);
}
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);
}
}
Expand All @@ -360,7 +360,7 @@ private <T> List<T> 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);
}

/**
Expand All @@ -387,9 +387,9 @@ private <T> Answer<T> 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");
Expand All @@ -409,9 +409,9 @@ private <T> Answer<T> 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));
};
};
}
Expand Down Expand Up @@ -459,10 +459,10 @@ private static <T> 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;
}
Expand Down Expand Up @@ -562,7 +562,7 @@ public Builder configureHttpClient(Consumer<HttpClient.Builder> 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<HttpClient> decorator) {
requireNonNull(decorator, "decorator");
Expand Down
Loading