fix(inbound)!: 네 전송이 같은 실패에 같은 코드와 로그로 답한다
문제(round7 리뷰 RR7-01-03~06): - 분산 락 timeout(LockAcquisitionTimeoutException)이 ApiErrorCarrier가 아니어서 web·GraphQL·gRPC 모두 500 INTERNAL_ERROR(재시도 불가)와 "unhandled" ERROR로 답한다. 레지스트리·runbook·Javadoc은 409 재시도 가능을 약속한다. web은 carrier가 되어도 Retry-After 표에 이 코드가 없어 헤더가 빠진다. - 다른 예외로 감싼 carrier를 gRPC만 원인 사슬에서 찾고 web·GraphQL· STOMP는 500 INTERNAL_ERROR로 답하며 SQL 원인째 ERROR로 남긴다. - gRPC 서비스가 IllegalArgumentException을 원인으로 든 raw status를 던지면 INTERNAL_ERROR·ERROR(입력이 든 메시지 첨부)이고, onError로 넘기면 BAD_PARAMETER·WARN이다. - STOMP @MessageMapping 앞에서 Spring이 거부한 클라이언트 메시지(읽지 못한 payload, 비었거나 검증에 걸린 payload, 변환되지 않는 @DestinationVariable·@Header)를 ERROR와 예외 메시지(받은 JSON 조각· 값)로 남긴다. 고른 방법: - shared-contract ApiErrorCarrier.firstIn(Throwable): 원인 사슬의 첫 carrier를 찾는다(자기 자신 포함, 사슬이 돌면 멈춤). web 처리기 둘, GraphQL 매퍼, gRPC 인터셉터, STOMP advice와 ERROR 프레임이 모두 이 함수를 쓰고 gRPC carrierOf와 STOMP의 carrier 루프는 지웠다. 로그 줄은 찾은 carrier로 정해 감싼 persistence 실패도 분류 한 줄만 남는다 (소유자 결정 2026-11-06 (a)). - LockAcquisitionTimeoutException이 ApiErrorCarrier를 구현한다. errorCode() 반환 타입은 OperationalError로 둔다(공변 반환, 호출부 변경 없음). RetryAfterAdvisor에 LOCK_ACQUISITION_TIMEOUT=1(레지스트리 값)을 더한다. 버린 안: web 전용 @ExceptionHandler — GraphQL·gRPC가 그대로 남는다. - gRPC close는 status 예외를 벗긴 실패 하나(failureBehind)로 carrier·IAE 판정과 로그를 모두 한다. 버린 안: closeWithError에서 status를 다시 만드는 것 — 판정과 로그가 또 다른 값을 볼 수 있다. - ServerFailureLog.refused(code, failure): refusedArgument와 같은 WARN 한 줄(타입만, 메시지·예외 없음). STOMP advice가 받은 메시지가 실린 MessageConversionException과 MethodArgumentNotValidException을 VALIDATION_FAILED, @DestinationVariable·@Header 대상 ConversionFailedException을 BAD_PARAMETER로 남긴다(web이 같은 실패에 답하는 코드). 응답을 쓰다 난 변환 실패는 받은 메시지가 없어 ERROR로 남는다. 위험·한계: - 응답이 바뀐다: 락 timeout 500 → 409(+Retry-After: 1), 감싼 carrier 500 → 그 carrier 코드, IAE가 감싼 carrier 400 → carrier 코드, gRPC가 던진 IAE 원인 raw status INTERNAL → INVALID_ARGUMENT. 업그레이드 안내 B-45·B-46과 5절에 적었다. - STOMP 쓰기/읽기 변환 실패 구분은 Spring 7.0.9 변환기가 읽기 실패에만 failedMessage를 싣는 데 기댄다(바이트코드로 확인). 바뀌면 aReplyTheConverterCannotWriteIsLoggedAtErrorWithTheFailure가 실패한다. - 고치지 않은 같은 모양(범위 밖, 보고에 적음): RetryAfterAdvisor 표에서 빠진 레지스트리 값 7개, GraphQL @Argument BindException의 INTERNAL_ERROR·ERROR, STOMP 필수 header 누락의 ERROR. 검증(desktop, flock /tmp/claude-gates/heavy.lock, 로그 ~/r8-f1-logs/): - RED(기준73d39212+ 테스트만): 7개 leaf에서 17건 실패, 모두 위 결함의 값(500 INTERNAL_ERROR, INTERNAL, ERROR + 입력 메시지 등). red.log, red-websocket.log - GREEN(이 트리b540d48e): shared-contract 269, application-core 413(skip 19, 이전부터), web 334, graphql 401, grpc 74, websocket 105, app-bootstrap 225(skip 4, 이전부터) 실패 0. green-test.log - :ci :verifyDependencyLocks --warning-mode=fail rc=0 - :sample-portfolio:check :sample-portfolio:qualityCheck rc=0 - :verifyStrictLaneStages --dry-run, -p optional-platforms 같은 것 rc=0 - -p optional-platforms ci rc=0 - web·graphql·websocket systemTest, :conditionalTransportQualification rc=0(web 18, graphql 34+8, grpc 29, websocket 21+7) - :app-bootstrap:documentContractTest rc=0(66) - 바뀐 7개 leaf testQualityCheck rc=0 - scripts/verify-compose-profile-contracts.sh rc=0 BREAKING CHANGE: 분산 락 timeout은 409 LOCK_ACQUISITION_TIMEOUT (retryable, Retry-After: 1), 다른 예외로 감싼 carrier는 web·GraphQL에서도 그 carrier 코드, gRPC가 던진 IllegalArgumentException 원인 raw status는 INVALID_ARGUMENT로 답한다. 클라이언트는 error.code로 가르면 바꿀 것이 없다. 업그레이드 안내 B-45·B-46. Refs: docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md RR7-01-03, RR7-01-04, RR7-01-05, RR7-01-06
This commit is contained in:
@@ -4,7 +4,7 @@ category: CONFLICT
|
||||
error_codes: [LOCK_ACQUISITION_TIMEOUT]
|
||||
severity: P2
|
||||
owner: oncall
|
||||
last_updated: 2026-06-15
|
||||
last_updated: 2026-11-07
|
||||
status: stub
|
||||
---
|
||||
|
||||
@@ -12,7 +12,12 @@ status: stub
|
||||
|
||||
## Symptoms
|
||||
|
||||
- HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT`
|
||||
- HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT` and `Retry-After: 1`; GraphQL extension
|
||||
`code=LOCK_ACQUISITION_TIMEOUT`, gRPC trailer `error-code: LOCK_ACQUISITION_TIMEOUT` (`ABORTED`), all
|
||||
`retryable=true`. A 4xx answer, so no server ERROR line — look at the metric.
|
||||
- Before 2026-11-07 the template answered this as 500 `INTERNAL_ERROR` with an "unhandled exception"
|
||||
ERROR line (the exception was not an `ApiErrorCarrier`). A service on an older template sees that
|
||||
instead.
|
||||
- Distributed lock wait exceeded configured timeout; high contention on a resource
|
||||
|
||||
## Diagnosis
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
- 커밋: `34565130` High·P1 19건 · `1400dc15` 남은 발견·매뉴얼·생성 명령 · `5786126c` 남은 항목과 합친 뒤 결함 ·
|
||||
`7ef8d0b4` 재리뷰 기록 · `bbe944bd` 재리뷰 결함 · `ecc74b7d` 2차 재리뷰 기록·이 안내 · `1885bf8d` 2차 재리뷰 결함 ·
|
||||
`339cf8fd` 3차 확인 리뷰 기록 · `f40c03c6` 3차 확인 리뷰 Minor · `c2e55510` 마지막 확인 리뷰 기록 ·
|
||||
`2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) — `docs(...)` 커밋은 문서만 바꾼다
|
||||
`2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · r8-f1 전송 오류 처리(2026-11-07, B-45·B-46) — `docs(...)` 커밋은 문서만 바꾼다
|
||||
- 근거 문서: `docs/reviews/2026-11-01-maturity-review/README.md` 13~16절, `docs/reviews/2026-11-03-rereview/README.md`
|
||||
4·6·8~13절, 각 커밋의 `BREAKING CHANGE:` 꼬리말
|
||||
- 아래 표의 각 줄은 위 범위의 diff와 코드로 확인했다. 확인하지 못한 것은 그 자리에 "확인 못 함"으로 적었고 9절에
|
||||
@@ -100,6 +100,8 @@
|
||||
| B-31 | 핸들러 밖 오류(`/error` 디스패치)를 `EnvelopeErrorController`가 실패 Envelope로 답한다. 전에는 Boot `/error` 맵이 `success:true`로 감싸져 요청 경로까지 실려 나갔다. 기본 JWT 체인에서 익명 400이 401로 바뀌지 않는다. 4xx·5xx 본문은 `success:true`로 감싸지 않는다. 보안 체인이 `DispatcherType.ERROR`를 허용한다 | 오류 본문 모양이 바뀐다. 자기 SecurityFilterChain이 ERROR 디스패치를 막으면 400이 401로 나간다 | 자기 체인에 `auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`을 넣는다(템플릿 `SecurityConfig`와 같게) | `bbe944bd` · `src/adapter/inbound/web/.../error/EnvelopeErrorController.java`, `.../auth/SecurityConfig.java` |
|
||||
| B-32 | 새·바뀐 오류 코드: 비동기 요청 timeout 500 `INTERNAL_ERROR` → 503 `REQUEST_TIMEOUT`(retryable). `IDEMPOTENCY_KEY_INVALID` 400(`details.reason`=`MISSING`·`MALFORMED`, `IdempotencyKeyHeader.parse`를 쓰는 엔드포인트, sample은 `BAD_PARAMETER`에서 바뀜). web-advanced 예외 10종이 모두 500 `INTERNAL_ERROR`였다가 각자 코드(`ADMISSION_REFUSED` 503 등) | 코드로 분기하던 클라이언트가 새 코드를 모른다 | 클라이언트 분기표에 더한다. web-advanced 표는 `src/adapter/inbound/web-advanced/README.md` 「오류 응답」 | `1400dc15` · `src/adapter/inbound/web/.../error/WebTransportError.java`, `HttpStatusErrorCodes.java`, `src/adapter/inbound/web-advanced/.../error/WebAdvancedError.java` |
|
||||
| B-33 | DB 실패 분류: 낙관적 잠금 충돌 500 → 409 `DB_OPTIMISTIC_CONFLICT`. 커밋 단계 연결 끊김(08xxx, 40003 등)을 재시도 가능으로 답하던 것 → 500 `DB_COMPLETION_UNKNOWN`(retryable=false) | 응답 status·code가 바뀐다 | 409는 다시 읽고 재시도, `DB_COMPLETION_UNKNOWN`은 업무 데이터로 결과를 확인 | `34565130`, `1400dc15` · `src/adapter/outbound/persistence-jpa/.../failure/PersistenceExceptionTranslator.java` |
|
||||
| B-45 | 분산 락 timeout(`LockAcquisitionTimeoutException`): 500 `INTERNAL_ERROR`(retryable=false) → 409 `LOCK_ACQUISITION_TIMEOUT`(retryable=true, `Retry-After: 1`). GraphQL extension `code`·`retryable`, gRPC `ABORTED` + trailer `error-code`도 같은 코드. 예외가 `ApiErrorCarrier`가 되어 레지스트리가 약속한 값으로 답한다. 4xx라 "unhandled exception" ERROR 줄이 사라진다 | 500을 "재시도 금지"로 읽던 클라이언트가 이제 409를 받는다. 이 예외에 자기 `@ExceptionHandler`를 둔 서비스는 그쪽 응답이 그대로 나간다 | `Retry-After` 뒤 같은 요청을 다시 보내게 한다. 자기 처리기를 두었다면 지워도 된다 | r8-f1(2026-11-07, 재리뷰 RR7-01-04) · `src/application-core/.../lock/LockAcquisitionTimeoutException.java`, `src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java` |
|
||||
| B-46 | 다른 예외로 감싼 carrier: web·GraphQL도 gRPC처럼 원인 사슬의 첫 carrier 코드로 답한다(전에는 500 `INTERNAL_ERROR`). `IllegalArgumentException`이 carrier를 감쌌으면 `BAD_PARAMETER` 대신 그 carrier 코드다. STOMP ERROR 프레임의 `error-code`도 `IllegalArgumentException` 뒤의 carrier를 그 코드로 낸다. gRPC는 `Status.INVALID_ARGUMENT.withCause(iae)`처럼 `IllegalArgumentException`을 원인으로 든 raw status를 던져도 `onError`로 넘긴 것과 같이 `INVALID_ARGUMENT`·`BAD_PARAMETER`다(전에는 던지면 `INTERNAL`) | 감싼 실패에 500·`INTERNAL`을 받던 클라이언트가 이제 그 carrier 코드(예: 503 `DB_UNAVAILABLE`)를 받는다 | 클라이언트 분기는 `error.code`로 한다(바꿀 것 없음). 감싼 실패를 일부러 500으로 보내려면 감싸지 말고 `IllegalStateException`을 던진다 | r8-f1(2026-11-07, 소유자 결정 2026-11-06, 재리뷰 RR7-01-05·RR7-01-03) · `src/shared-contract/.../error/ApiErrorCarrier.java` `firstIn`, 네 전송의 오류 처리기 |
|
||||
|
||||
### 3.4 빌드 게이트·아키텍처 규칙 — `ci`가 빨개진다
|
||||
|
||||
@@ -243,6 +245,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur
|
||||
| 멱등성(전이의 operation id·release·inspect, 2026-11-06) | owner token이 같아도 호출이 claim과 다른 operation id를 대면 PostgreSQL·in-memory fake도 다섯 전이(start·renew·complete·fail·release)를 `OPERATION_CONFLICT`로 거절하고 기록을 바꾸지 않는다(전에는 적용했다. Redis는 전부터 거절). in-memory fake의 claim은 같은 token·다른 operation에 `OwnerOperationConflict`(전에는 `InProgress`), inspect는 `OPERATION_CONFLICT`(전에는 `IN_PROGRESS_OTHER`). PostgreSQL·fake의 inspect는 완료된 기록에도 `OPERATION_CONFLICT`(전에는 응답을 재생). PostgreSQL complete는 같은 operation id를 쓴 다른 attempt에 `NOT_OWNER`(전에는 `ALREADY_COMPLETED_SAME_RESULT`). Redis release는 기록이 없으면 `ABSENT`(전에는 `ALREADY_RELEASED_SAME_OPERATION`)이고 핸들 revision을 본다: 같은 attempt가 넘겨받기 전 핸들로 release하면 `NOT_OWNER`(전에는 지금의 claim을 지웠다) | 템플릿의 호출자(`IdempotencyExecutor`)는 늘 claim의 operation id를 넘기고 release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 전이마다 다른 operation id를 넘기던 코드는 이제 `OPERATION_CONFLICT`를 받는다 — `IdempotencyOwner.claimOperationId()`를 넘긴다. Redis release의 `ALREADY_RELEASED_SAME_OPERATION`을 기다리던 코드는 `ABSENT`도 "해제됨"으로 읽는다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | 2026-11-06(소유자 결정 "(a)로 진행", 라운드6 02 Declined) · `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `RedisIdempotencyStoreAdapter.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` |
|
||||
| 빌드 단계(HTTP client) | `httpClientFailureInjectionTest`(Toxiproxy 장애 주입)가 `mainCheck`에서 빠졌다. `integrationCheck`에만 있고, main push·nightly의 `integration-main.yml` `integration-check` job이 돌린다 | main push마다 같은 lane이 `main-check`·`integration-check` 두 job에서 두 번 돌던 것이 한 번이 된다. 로컬에서 `mainCheck`만 돌리면 이 lane은 돌지 않는다(`integrationCheck`로 돌린다) | r9 · `src/adapter/outbound/httpclient/build.gradle` |
|
||||
| 서버 로그(GraphQL·gRPC·STOMP) | carrier로 답한 실패를 web과 같은 줄(shared-contract `ServerFailureLog`)로 ERROR에 남긴다: persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. gRPC는 ` (method=…)`, GraphQL은 ` (executionId=…)`를 붙인다. gRPC는 인식 못 한 실패(`INTERNAL_ERROR`)도 `unhandled failure on <method> …`로 남긴다. 클라이언트가 취소한 호출은 남기지 않고, 서비스가 `CANCELLED` status로 끝낸 살아 있는 호출은 남긴다. raw status는 넘겼든 던졌든 설명을 남기지 않는다(원인 예외가 있으면 그것만 붙인다). `IllegalArgumentException`(`BAD_PARAMETER`)은 web과 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입>`(메시지 없음)으로 남긴다. STOMP `@MessageMapping` 실패는 Spring의 `Unhandled exception from message handler method`(예외 전체) 대신 같은 줄로 남는다 | ERROR 로그가 늘어난다(전에는 gRPC가 아무것도 남기지 않았다). GraphQL·gRPC·STOMP는 잘못된 입력마다 WARN 한 줄이 생긴다. STOMP에서 Spring 문구로 경보를 걸었다면 고친다. `IDEMPOTENCY_RECOVERY_REQUIRED`의 scope digest를 모든 전송에서 찾을 수 있다(`docs/runbooks/idempotency-unavailable.md`) | r9 · `src/shared-contract/.../error/ServerFailureLog.java`, `GrpcExceptionHandlingInterceptor.java`, `GraphQlWireErrorMapper.java`, `StompHandlerFailureLog.java` |
|
||||
| 서버 로그(STOMP 거부·감싼 carrier, 2026-11-07) | `@MessageMapping` 앞에서 Spring이 거부한 메시지를 WARN 한 줄 `request refused as <code> by <예외 타입>`으로 남긴다: 읽지 못한 payload(`MessageConversionException`)·비었거나 검증에 걸린 payload(`MethodArgumentNotValidException`)는 `VALIDATION_FAILED`, 변환되지 않는 `@DestinationVariable`·`@Header`(`ConversionFailedException`)는 `BAD_PARAMETER`. 전에는 ERROR에 예외 메시지(받은 JSON 조각·값)까지 남겼다. 응답을 쓰지 못한 변환 실패는 그대로 ERROR. 네 전송 모두 감싼 carrier를 그 carrier 줄로 남긴다(감싼 persistence 실패는 분류만, SQL 원인 없음) | ERROR 경보가 클라이언트의 잘못된 메시지에 울리지 않는다. 그 실패를 찾던 로그 검색은 WARN으로 바꾼다 | r8-f1(재리뷰 RR7-01-06·RR7-01-05) · `src/adapter/inbound/websocket/.../stomp/StompHandlerFailureLog.java`, `src/shared-contract/.../error/ServerFailureLog.java` `refused` |
|
||||
| sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` |
|
||||
| Flyway 잠금 | Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션 대신 세션에 둔다. Spring Boot의 Flyway는 module-defaults `spring.flyway.postgresql.transactional-lock: false`, 템플릿이 직접 만드는 Flyway(멱등성·알림·sample stream, schema-per-tenant, testkit `MigrationContractRunner`)는 `FlywaySchemaPolicy.configure()`, messaging inbox stream은 같은 값을 직접 넣는다. 운영 코드의 `Flyway.configure()` 직접 호출은 `JpaProductionArchitectureTest`가 거부한다 | Flyway 기본값에서는 동시 인덱스 마이그레이션이 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않았다. 이제 끝난다. 마이그레이션은 잠금을 잡은 연결 하나로 돈다. transaction 모드 PgBouncer 뒤에서는 잠금 해제가 다른 서버 연결로 가 다음 배포가 기다릴 수 있으니 마이그레이션은 직접 연결이나 session 모드 pool로 돌린다. 배포 도구는 이 repo 밖이라 2절 15번으로 맞춘다 | 재리뷰 round6 RR6-03-01 · `persistence-jpa.yml`, `.../migration/FlywaySchemaPolicy.java`, `docs/jpa/migration-guide.md` "Who may change the schema"·"Concurrent index builds" |
|
||||
| 성능 lane(HTTP client·Mongo) | httpclient `LargeBodyResourceTest`의 힙 상한(32 MiB 스트리밍 중 힙 증가 16 MiB 미만)을 매번 단언한다. 전에는 `-Pperformance.assertions.enabled=true`일 때만 단언하고 아니면 건너뛴다는 줄만 찍었다. Mongo `MongoResourceBudgetLaneTest`는 표준 gate 전체(p99 500ms, pool 대기 250ms, 힙 512 MiB, examined/returned 10, spill 금지)를 Gradle 밖 실행에서도 단언한다(B-43) | 손으로 돌린 `performanceCheck`가 상한을 실제로 재므로, 전에는 통과하던 느린 기계에서 실패할 수 있다 | B4(2026-11-06) · `LargeBodyResourceTest`, `MongoResourceBudgetLaneTest` |
|
||||
@@ -294,6 +297,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur
|
||||
|
||||
- CORS가 켜져 있으면 `Retry-After`·`X-Request-Id`·`X-Correlation-Id`·`traceparent` 등이 `Access-Control-Expose-Headers`에 있다(§3).
|
||||
- 새 코드: `REQUEST_TIMEOUT`(503, retryable), web-advanced를 쓰는 서비스는 10종(3.3절 B-32).
|
||||
- 분산 락 timeout은 409 `LOCK_ACQUISITION_TIMEOUT`(retryable, `Retry-After: 1`)이다. 전에는 500 `INTERNAL_ERROR`였다(3.3절 B-45).
|
||||
- 프론트 계약 문서(`clean-architecture-frontend-template` `docs/architecture/backend-api-and-server-state-contract.md` §4.1·§6)는
|
||||
`docs/web/http-contract.md`를 가리켜야 한다.
|
||||
- 프론트 세션에 넘긴 인계 문서(세션 scratchpad라 지워질 수 있음):
|
||||
|
||||
@@ -121,7 +121,8 @@ application/platform namespace split.
|
||||
|
||||
모든 client 에러는 `error/GraphQlWireErrorMapper` 하나를 거친다 — 전송 interceptor, 실행 전
|
||||
pipeline(instrumentation), data fetcher resolver 세 곳이 같은 bean 을 받는다. 순서는 플랫폼 거부
|
||||
(예외가 구현한 `error/GraphQlPlatformRejection`) → `ApiErrorCarrier`(자기 `ApiErrorCode`) → 등록된
|
||||
(예외가 구현한 `error/GraphQlPlatformRejection`) → `ApiErrorCarrier`(자기 또는 원인 사슬의 첫 carrier의
|
||||
`ApiErrorCode`) → 등록된
|
||||
application 매핑(`GraphQlExceptionResolver`) → `IllegalArgumentException`=`BAD_PARAMETER`. 어디에도 안
|
||||
걸린 예외는 `INTERNAL_ERROR` 로 가려지고, 같은 executionId 로 ERROR 로그 한 줄이 남는다. client 문구는
|
||||
shared-contract `ClientErrorMessages`(Category 별 한국어 표), `retryable` 은 코드의 값이다. Category →
|
||||
|
||||
@@ -66,7 +66,9 @@ instrumentation, data fetcher resolver 세 곳이 같은 bean 을 받는다).
|
||||
|
||||
1. **플랫폼 거부** — 플랫폼 예외가 `error/GraphQlPlatformRejection`(wire code·shared `Category`·
|
||||
필요하면 wire category/constraint)을 구현한다. `instanceof` 사슬로 등록하던 두 번째 목록은 없다.
|
||||
2. **`ApiErrorCarrier`** — 자기 `ApiErrorCode` 로 매핑. shared-contract 의 `MappingException`·
|
||||
2. **`ApiErrorCarrier`** — 실패 자신이나 원인 사슬의 첫 carrier(`ApiErrorCarrier.firstIn`, web·gRPC·STOMP와
|
||||
같은 함수)를 그 `ApiErrorCode` 로 매핑. 로그 줄도 감싼 예외가 아니라 그 carrier 로 정한다(재리뷰 RR7-01-05).
|
||||
shared-contract 의 `MappingException`·
|
||||
`AdapterDisabledException`·`PersistenceFailureException`(JPA 예외 포함)·`DependencyFailureException`,
|
||||
application 의 멱등성 예외, DataLoader 키 실패(`GraphQlBatchLoadException`, **등록된 `ApiErrorCode`
|
||||
만** — 소유자 결정 25)가 모두 여기로 온다.
|
||||
|
||||
+20
-14
@@ -11,6 +11,7 @@ import graphql.GraphQLError;
|
||||
import java.util.EnumMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.graphql.execution.ErrorType;
|
||||
@@ -103,12 +104,14 @@ public final class GraphQlWireErrorMapper {
|
||||
/**
|
||||
* Maps a failure from any stage.
|
||||
*
|
||||
* <p>Order: a platform rejection, then an {@link ApiErrorCarrier}, then the application's
|
||||
* registered mappings, then {@link IllegalArgumentException} as {@code BAD_PARAMETER} (the same
|
||||
* answer every transport gives), and finally the masked internal error. Platform rejections come
|
||||
* first: an authorization denial raised from inside a resolver means the same thing to a client
|
||||
* as one raised before execution. A registered mapping outranks the argument rule so an
|
||||
* application that models its own {@code IllegalArgumentException} subtype keeps its code.
|
||||
* <p>Order: a platform rejection, then an {@link ApiErrorCarrier} — the failure itself or the
|
||||
* first one in its cause chain, as on every transport (review 2026-11-06 RR7-01-05) — then the
|
||||
* application's registered mappings, then {@link IllegalArgumentException} as {@code
|
||||
* BAD_PARAMETER} (the same answer every transport gives), and finally the masked internal error.
|
||||
* Platform rejections come first: an authorization denial raised from inside a resolver means the
|
||||
* same thing to a client as one raised before execution. A registered mapping outranks the
|
||||
* argument rule so an application that models its own {@code IllegalArgumentException} subtype
|
||||
* keeps its code.
|
||||
*/
|
||||
public GraphQlWireError map(Throwable failure, GraphQlErrorContext context) {
|
||||
if (failure instanceof GraphQlPlatformRejection rejection) {
|
||||
@@ -123,15 +126,16 @@ public final class GraphQlWireErrorMapper {
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes {@link ServerFailureLog}'s line for a failure answered with a shared code: a carrier's
|
||||
* line at ERROR, or nothing for a client-side carrier; an unmapped {@link
|
||||
* IllegalArgumentException} the WARN line naming its type, as on every transport.
|
||||
* Writes {@link ServerFailureLog}'s line for a failure answered with a shared code: the carrier's
|
||||
* line at ERROR — the carrier's, not a wrapper's — or nothing for a client-side carrier; an
|
||||
* unmapped {@link IllegalArgumentException} the WARN line naming its type, as on every transport.
|
||||
*/
|
||||
private static void logAnswer(
|
||||
Throwable failure, ApiErrorCode shared, GraphQlErrorContext context) {
|
||||
String suffix = " (executionId={})";
|
||||
if (failure instanceof ApiErrorCarrier) {
|
||||
ServerFailureLog.of(failure, shared)
|
||||
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
|
||||
if (carrier.isPresent()) {
|
||||
ServerFailureLog.of(carrier.get(), shared)
|
||||
.ifPresent(line -> LOG.error(line.format(suffix), line.arguments(context.executionId())));
|
||||
} else if (failure instanceof IllegalArgumentException refused) {
|
||||
ServerFailureLog line = ServerFailureLog.refusedArgument(refused);
|
||||
@@ -191,14 +195,16 @@ public final class GraphQlWireErrorMapper {
|
||||
}
|
||||
|
||||
/**
|
||||
* The shared code a failure carries, or {@code null}.
|
||||
* The shared code a failure carries, or {@code null}: the code of the first carrier in its cause
|
||||
* chain.
|
||||
*
|
||||
* <p>An {@link IllegalArgumentException} the application did not register a mapping for is {@link
|
||||
* OperationalError#BAD_PARAMETER}, as it is on the web, gRPC and STOMP transports.
|
||||
*/
|
||||
private ApiErrorCode sharedCodeOf(Throwable failure) {
|
||||
if (failure instanceof ApiErrorCarrier carrier) {
|
||||
return carrier.errorCode();
|
||||
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
|
||||
if (carrier.isPresent()) {
|
||||
return ((ApiErrorCarrier) carrier.get()).errorCode();
|
||||
}
|
||||
if (failure instanceof IllegalArgumentException && !applicationMappings.maps(failure)) {
|
||||
return OperationalError.BAD_PARAMETER;
|
||||
|
||||
+67
-1
@@ -11,9 +11,11 @@ import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyExcept
|
||||
import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyInFlightException;
|
||||
import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException;
|
||||
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import dev.caskeleton.shared.error.PersistenceFailureException;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
@@ -231,8 +233,72 @@ class GraphQlWireErrorMapperTest {
|
||||
null);
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.Test
|
||||
void aLockAcquisitionTimeoutKeepsItsRetryableCode() {
|
||||
// given
|
||||
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
|
||||
RuntimeException failure =
|
||||
new LockAcquisitionTimeoutException("orders/42", Duration.ofSeconds(3));
|
||||
|
||||
// when
|
||||
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
|
||||
|
||||
// then
|
||||
assertThat(error.extensions())
|
||||
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("retryable"))
|
||||
.containsExactly("LOCK_ACQUISITION_TIMEOUT", true);
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.Test
|
||||
void aCarrierWrappedInAnotherExceptionKeepsItsOwnCode() {
|
||||
// given
|
||||
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
|
||||
RuntimeException failure =
|
||||
new IllegalStateException("use case failed", persistenceFailureWithASqlCause());
|
||||
|
||||
// when
|
||||
GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test());
|
||||
|
||||
// then
|
||||
assertThat(error.extensions())
|
||||
.extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category"))
|
||||
.containsExactly("DB_UNAVAILABLE", "DEPENDENCY");
|
||||
}
|
||||
|
||||
@org.junit.jupiter.api.Test
|
||||
void aWrappedPersistenceFailureIsLoggedByItsClassificationWithoutTheWrapperOrTheSqlCause() {
|
||||
// given
|
||||
GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking();
|
||||
RuntimeException failure =
|
||||
new IllegalStateException("use case failed", persistenceFailureWithASqlCause());
|
||||
|
||||
// when
|
||||
List<ILoggingEvent> logged =
|
||||
loggedWhile(() -> mapper.map(failure, GraphQlErrorContext.of("exec-9")));
|
||||
|
||||
// then
|
||||
assertThat(logged)
|
||||
.singleElement()
|
||||
.extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy)
|
||||
.containsExactly(
|
||||
"persistence failure classified as DB_UNAVAILABLE (category=TRANSIENT_DEPENDENCY,"
|
||||
+ " retryable=true) (executionId=exec-9)",
|
||||
null);
|
||||
}
|
||||
|
||||
private static PersistenceFailureException persistenceFailureWithASqlCause() {
|
||||
return new PersistenceFailureException(
|
||||
OperationalError.DB_UNAVAILABLE,
|
||||
"08006",
|
||||
new SQLException("jdbc:postgresql://db.internal/customer?password=secret", "08006"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Every line this package writes while {@code action} runs: the mapper's own and the masking
|
||||
* resolver's, so a failure that should have been classified but was masked shows up too.
|
||||
*/
|
||||
private static List<ILoggingEvent> loggedWhile(Runnable action) {
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(GraphQlWireErrorMapper.class);
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(GraphQlWireErrorMapper.class.getPackageName());
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
|
||||
@@ -146,7 +146,12 @@ handler throw, listener callback throw, `responseObserver.onError(...)`, raw
|
||||
- **`IllegalArgumentException`** 은 `BAD_PARAMETER`(`INVALID_ARGUMENT`) — 모든 전송이 같다.
|
||||
- **`ApiErrorCode` 추출**: feature 예외는 `ApiErrorCarrier`(이 모듈이 제공하는 전송-중립 hook)를
|
||||
구현해 자신의 `ApiErrorCode` 를 노출한다. shared-contract 의 `PersistenceFailureException` /
|
||||
`DependencyFailureException`(outbound 어댑터에서 올라온 분류된 실패)도 직접 인식한다.
|
||||
`DependencyFailureException`(outbound 어댑터에서 올라온 분류된 실패)도 직접 인식한다. carrier 는 원인
|
||||
사슬의 첫 것을 shared-contract `ApiErrorCarrier.firstIn` 으로 찾는다. web·GraphQL·STOMP 도 같은 함수다.
|
||||
- **raw status 를 던지든 `onError` 로 넘기든 같은 판정**: 던진 raw status 는 그 예외 자체가 원인 자리에 와서
|
||||
`close` 에 닿는다. 그래서 인터셉터는 status 예외를 벗긴 뒤의 실패 하나로 carrier·`IllegalArgumentException`
|
||||
판정과 로그를 모두 한다. `Status.INVALID_ARGUMENT.withCause(iae).asRuntimeException()` 은 던져도 넘겨도
|
||||
`BAD_PARAMETER`·WARN 한 줄이다(재리뷰 RR7-01-03 전에는 던지면 `INTERNAL_ERROR`·ERROR 에 메시지까지 남았다).
|
||||
- **leak 방지**: 인식된 코드는 안정적 `code` 문자열만 status description/trailer 로 노출하고, raw
|
||||
예외 메시지(SQLState/업스트림 세부를 담을 수 있음)는 절대 클라이언트에 내보내지 않는다. 인식되지
|
||||
않은 예외와 raw gRPC status/description은 원래 status를 신뢰하지 않고 `Status.INTERNAL` +
|
||||
|
||||
+24
-30
@@ -13,6 +13,7 @@ import io.grpc.ServerInterceptor;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.StatusException;
|
||||
import io.grpc.StatusRuntimeException;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -28,7 +29,8 @@ import org.slf4j.LoggerFactory;
|
||||
* ApiErrorCarrier} hook — implemented by a feature throwable (the gRPC {@link ApiErrorException}
|
||||
* carrying a mapped domain code) and by the shared-contract {@code PersistenceFailureException} /
|
||||
* {@code DependencyFailureException}, so a single {@code instanceof ApiErrorCarrier} branch covers
|
||||
* them all. An {@link IllegalArgumentException} maps to {@link OperationalError#BAD_PARAMETER}
|
||||
* them all, found with {@link ApiErrorCarrier#firstIn} anywhere in the cause chain as on every
|
||||
* transport. An {@link IllegalArgumentException} maps to {@link OperationalError#BAD_PARAMETER}
|
||||
* ({@code INVALID_ARGUMENT}), as on every other transport. Any other unrecognised exception or raw
|
||||
* gRPC status maps to {@link Status#INTERNAL} with {@link OperationalError#INTERNAL_ERROR}. The
|
||||
* client sees the stable code, category and retryability in the trailers and the shared category
|
||||
@@ -128,20 +130,23 @@ public class GrpcExceptionHandlingInterceptor implements ServerInterceptor {
|
||||
}
|
||||
|
||||
String method = delegate.getMethodDescriptor().getFullMethodName();
|
||||
Throwable carrier = carrierOf(status.getCause());
|
||||
// A thrown raw status arrives wrapped in itself (closeWithError); one passed to onError
|
||||
// does not. Judging the failure behind it answers both the same way (RR7-01-03).
|
||||
Throwable failure = failureBehind(status.getCause());
|
||||
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
|
||||
ApiErrorCode code;
|
||||
if (carrier != null) {
|
||||
code = ((ApiErrorCarrier) carrier).errorCode();
|
||||
ServerFailureLog.of(carrier, code)
|
||||
if (carrier.isPresent()) {
|
||||
code = ((ApiErrorCarrier) carrier.get()).errorCode();
|
||||
ServerFailureLog.of(carrier.get(), code)
|
||||
.ifPresent(line -> log.error(line.format(" (method={})"), line.arguments(method)));
|
||||
} else if (status.getCause() instanceof IllegalArgumentException refused) {
|
||||
} else if (failure instanceof IllegalArgumentException refused) {
|
||||
code = OperationalError.BAD_PARAMETER;
|
||||
ServerFailureLog line = ServerFailureLog.refusedArgument(refused);
|
||||
log.warn(line.format(" (method={})"), line.arguments(method));
|
||||
} else {
|
||||
code = OperationalError.INTERNAL_ERROR;
|
||||
if (!delegate.isCancelled()) {
|
||||
logUnrecognised(method, status);
|
||||
logUnrecognised(method, status, failure);
|
||||
}
|
||||
}
|
||||
super.close(statusMapper.statusFor(code), statusMapper.trailersFor(code));
|
||||
@@ -153,43 +158,32 @@ public class GrpcExceptionHandlingInterceptor implements ServerInterceptor {
|
||||
call.close(Status.fromThrowable(exception).withCause(exception), new Metadata());
|
||||
}
|
||||
|
||||
private static void logUnrecognised(String method, Status status) {
|
||||
// The cause, when there is one, is the last argument and so the logged exception; the raw
|
||||
private static void logUnrecognised(String method, Status status, Throwable failure) {
|
||||
// The failure, when there is one, is the last argument and so the logged exception; the raw
|
||||
// description is never logged.
|
||||
log.error(
|
||||
"unhandled failure on {} answered as {} (status={})",
|
||||
method,
|
||||
OperationalError.INTERNAL_ERROR.code(),
|
||||
status.getCode(),
|
||||
failureBehind(status.getCause()));
|
||||
failure);
|
||||
}
|
||||
|
||||
/**
|
||||
* The exception to attach for an unrecognised failure. A thrown raw status reaches {@code close}
|
||||
* as the status's own cause ({@link #closeWithError}), and its message is {@code "CODE:
|
||||
* description"} — the description that may echo input. So a raw status is never attached: only
|
||||
* the first cause behind it that is not one, if any (review 2026-11-05 RR6-01-05).
|
||||
* The failure a status was closed for, which is what the interceptor judges and attaches. A
|
||||
* thrown raw status reaches {@code close} as the status's own cause ({@link #closeWithError}),
|
||||
* and its message is {@code "CODE: description"} — the description that may echo input. So a raw
|
||||
* status is never the failure: the first cause behind it that is not one is, if any (review
|
||||
* 2026-11-05 RR6-01-05). A raw status passed to {@code onError} reaches {@code close} with its
|
||||
* own cause already, so both ways of ending a call with the same status are judged alike (review
|
||||
* 2026-11-06 RR7-01-03).
|
||||
*/
|
||||
private static Throwable failureBehind(Throwable cause) {
|
||||
Throwable current = cause;
|
||||
while (current instanceof StatusRuntimeException || current instanceof StatusException) {
|
||||
while ((current instanceof StatusRuntimeException || current instanceof StatusException)
|
||||
&& !(current instanceof ApiErrorCarrier)) {
|
||||
current = current.getCause();
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/** The first {@link ApiErrorCarrier} in the cause chain, or {@code null}. */
|
||||
private static Throwable carrierOf(Throwable throwable) {
|
||||
Throwable current = throwable;
|
||||
while (current != null) {
|
||||
if (current instanceof ApiErrorCarrier) {
|
||||
return current;
|
||||
}
|
||||
if (current.getCause() == current) {
|
||||
break;
|
||||
}
|
||||
current = current.getCause();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
+97
@@ -16,10 +16,13 @@ import io.grpc.MethodDescriptor;
|
||||
import io.grpc.ServerCall;
|
||||
import io.grpc.ServerCallHandler;
|
||||
import io.grpc.Status;
|
||||
import io.grpc.stub.ServerCalls;
|
||||
import java.sql.SQLException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
@@ -327,6 +330,100 @@ class GrpcExceptionHandlingInterceptorTest {
|
||||
null);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(Ending.class)
|
||||
void aRawStatusAroundAnIllegalArgumentIsABadParameterHoweverTheServiceEndsTheCall(Ending ending) {
|
||||
// given
|
||||
RuntimeException rawStatus =
|
||||
Status.INVALID_ARGUMENT
|
||||
.withCause(new IllegalArgumentException("unknown recipient alice@example.com"))
|
||||
.asRuntimeException();
|
||||
|
||||
// when
|
||||
CapturingServerCall call = endUnaryCall(ending, rawStatus);
|
||||
|
||||
// then
|
||||
assertThat(call)
|
||||
.extracting(
|
||||
captured -> captured.status.getCode(),
|
||||
captured -> captured.trailers.get(GrpcStatusMapper.CODE_KEY))
|
||||
.containsExactly(Status.Code.INVALID_ARGUMENT, "BAD_PARAMETER");
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(Ending.class)
|
||||
void aRawStatusAroundAnIllegalArgumentIsLoggedAtWarnByItsTypeHoweverTheServiceEndsTheCall(
|
||||
Ending ending) {
|
||||
// given
|
||||
RuntimeException rawStatus =
|
||||
Status.INVALID_ARGUMENT
|
||||
.withCause(new IllegalArgumentException("unknown recipient alice@example.com"))
|
||||
.asRuntimeException();
|
||||
|
||||
// when
|
||||
List<ILoggingEvent> logged = loggedWhile(() -> endUnaryCall(ending, rawStatus));
|
||||
|
||||
// then
|
||||
assertThat(logged)
|
||||
.singleElement()
|
||||
.extracting(
|
||||
ILoggingEvent::getLevel,
|
||||
ILoggingEvent::getFormattedMessage,
|
||||
ILoggingEvent::getThrowableProxy)
|
||||
.containsExactly(
|
||||
Level.WARN,
|
||||
"request refused as BAD_PARAMETER by java.lang.IllegalArgumentException"
|
||||
+ " (method=test.Fixture/Call)",
|
||||
null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCarrierWrappedInAnotherExceptionIsAnsweredWithItsOwnCode() {
|
||||
// given
|
||||
IllegalStateException wrapper =
|
||||
new IllegalStateException(
|
||||
"use case failed",
|
||||
new PersistenceFailureException(
|
||||
OperationalError.DB_UNAVAILABLE,
|
||||
"08006",
|
||||
new SQLException("jdbc:postgresql://db.internal/customer", "08006")));
|
||||
|
||||
// when
|
||||
CapturingServerCall call = closeAfterThrowing(wrapper);
|
||||
|
||||
// then
|
||||
assertThat(call)
|
||||
.extracting(
|
||||
captured -> captured.status.getCode(),
|
||||
captured -> captured.trailers.get(GrpcStatusMapper.CODE_KEY))
|
||||
.containsExactly(Status.Code.UNAVAILABLE, "DB_UNAVAILABLE");
|
||||
}
|
||||
|
||||
/** The two ways grpc-java lets a unary service end its call with a failure. */
|
||||
enum Ending {
|
||||
THROWN,
|
||||
PASSED_TO_ON_ERROR;
|
||||
|
||||
ServerCallHandler<String, String> serviceFailingWith(RuntimeException failure) {
|
||||
return ServerCalls.asyncUnaryCall(
|
||||
(request, responseObserver) -> {
|
||||
if (this == THROWN) {
|
||||
throw failure;
|
||||
}
|
||||
responseObserver.onError(failure);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private CapturingServerCall endUnaryCall(Ending ending, RuntimeException failure) {
|
||||
CapturingServerCall call = new CapturingServerCall();
|
||||
ServerCall.Listener<String> listener =
|
||||
interceptor.interceptCall(call, new Metadata(), ending.serviceFailingWith(failure));
|
||||
listener.onMessage("request");
|
||||
listener.onHalfClose();
|
||||
return call;
|
||||
}
|
||||
|
||||
private static List<ILoggingEvent> loggedWhile(Runnable action) {
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(GrpcExceptionHandlingInterceptor.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
|
||||
@@ -208,9 +208,13 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
||||
supported-method 같은 bounded 구조 메타데이터로 `details`에 둔다. collection/map index와 key는
|
||||
field path에서 제거한다.
|
||||
- `ApiErrorCarrier`(shared `MappingException`·`AdapterDisabledException`·`PersistenceFailureException`·
|
||||
`DependencyFailureException`, application 멱등성 예외, adopter 예외)는 `handleCarrier` 분기
|
||||
`DependencyFailureException`, application 멱등성·분산 락 예외, adopter 예외)는 `handleCarrier` 분기
|
||||
하나로 매핑한다. 5xx 는 원인과 함께 로그를 남기고(persistence 는 분류만), retryable 코드는
|
||||
`RetryAfterAdvisor`로 `Retry-After`를 붙인다.
|
||||
- carrier 를 다른 예외로 감싸 던져도 같다. `handleUnknown`(그 밖의 예외)과 `handleIllegalArgument` 는
|
||||
원인 사슬의 첫 carrier(`ApiErrorCarrier.firstIn`)를 찾아 `handleCarrier` 로 넘긴다. 감싼
|
||||
persistence 실패도 500 `INTERNAL_ERROR` 와 SQL 원인 대신 그 분류 코드와 분류 한 줄로 남는다. GraphQL·gRPC·STOMP
|
||||
도 같은 함수를 쓴다(소유자 결정 2026-11-06, 재리뷰 RR7-01-05).
|
||||
- 개별 override 가 없는 Spring MVC 예외(필수 파라미터·헤더·part 누락, binding 실패 등)는
|
||||
`handleExceptionInternal` override 가 상태 코드 → 코드로 바꿔 같은 Envelope 로 보낸다. 503(Spring 의
|
||||
async 요청 시간 초과)은 `INTERNAL_ERROR` 가 아니라 `REQUEST_TIMEOUT`(503, retryable) 이다(리뷰 02-08).
|
||||
@@ -248,6 +252,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
||||
| `IdempotencyCompletionUnknownException` | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 503 (retryable=true) | action 이 돈 뒤 결과 기록(complete) 중 저장소가 응답하지 않음. 결과 불명 — 같은 키로 재전송, 새 키 금지(`docs/web/http-contract.md` §2, 재리뷰 RR-02-03). carrier 분기 |
|
||||
| `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 |
|
||||
| `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=true, `Retry-After: 2`) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 클라이언트 행동: 결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). 진단정보(scope digest)는 클라이언트 미도달 |
|
||||
| `LockAcquisitionTimeoutException` | `LOCK_ACQUISITION_TIMEOUT` | 409 (retryable=true, `Retry-After: 1`) | 분산 락을 `waitTime` 안에 못 잡음. 경합은 일시적이라 잠시 뒤 같은 요청을 다시 보낸다. carrier 분기(전에는 carrier 가 아니라 500 `INTERNAL_ERROR`, 재리뷰 RR7-01-04) |
|
||||
| `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 (retryable=false) | D8: `Idempotency-Key` 를 다른 본문으로 재사용. 다시 보내지 않는다(`docs/web/http-contract.md` §2). fingerprint/scope 노출 금지 |
|
||||
| `PersistenceFailureException` (JPA `JpaPersistenceException` 포함) | `ex.errorCode()` (사전분류 `DB_*`) | 코드 결정 | adapter-persistence translator 가 SQLState→`DB_*` 로 이미 분류, JPA 예외는 `FailureCategory`→`DB_*`. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**(SQLState/제약명 담음, 서버 로그 전용) |
|
||||
| `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 |
|
||||
@@ -521,6 +526,8 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML
|
||||
(web-advanced `ADMISSION_REFUSED` = 1초).
|
||||
- `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안
|
||||
같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2.
|
||||
- `LOCK_ACQUISITION_TIMEOUT` 은 1초(레지스트리 값). 표가 `Map.of` 의 상한인 10쌍을 채웠다. 더 넣으려면
|
||||
`Map.ofEntries` 로 바꾼다.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ package dev.caskeleton.adapter.inbound.web.error;
|
||||
/**
|
||||
* An {@link dev.caskeleton.shared.error.ApiErrorCarrier} that has bounded, client-safe structure to
|
||||
* put in {@code error.details} — a JSON pointer the client sent, field names from a server
|
||||
* allowlist. {@link GlobalExceptionHandler#handleCarrier(Exception)} copies it to the wire.
|
||||
* allowlist. {@link GlobalExceptionHandler#handleCarrier(Throwable)} copies it to the wire.
|
||||
*
|
||||
* <p>Never the exception message, a server value, or anything the caller may not read: what this
|
||||
* returns is published verbatim.
|
||||
|
||||
+17
-10
@@ -18,6 +18,7 @@ import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -86,12 +87,14 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
/**
|
||||
* An {@link IllegalArgumentException} is read as "the request was wrong" and answered 400, with
|
||||
* {@link ServerFailureLog#refusedArgument}'s WARN line — the exception type, never the message,
|
||||
* which may echo request input. The GraphQL, gRPC and STOMP adapters write the same line.
|
||||
* which may echo request input. The GraphQL, gRPC and STOMP adapters write the same line. A
|
||||
* carrier in its cause chain answers instead, as on every transport.
|
||||
*/
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
public ResponseEntity<Envelope<Void>> handleIllegalArgument(IllegalArgumentException ex) {
|
||||
if (ex instanceof ApiErrorCarrier) {
|
||||
return handleCarrier(ex);
|
||||
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(ex);
|
||||
if (carrier.isPresent()) {
|
||||
return handleCarrier(carrier.get());
|
||||
}
|
||||
ServerFailureLog line = ServerFailureLog.refusedArgument(ex);
|
||||
log.warn(line.format(""), line.arguments());
|
||||
@@ -155,9 +158,11 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
/**
|
||||
* Maps every {@link ApiErrorCarrier} — the shared-contract carriers ({@code MappingException},
|
||||
* {@code AdapterDisabledException}, {@code PersistenceFailureException}, {@code
|
||||
* DependencyFailureException}), the application's idempotency failures and any adopter carrier —
|
||||
* through its own {@link ApiErrorCode}. One branch, so the web adapter answers a carrier exactly
|
||||
* as the GraphQL, gRPC and STOMP adapters do.
|
||||
* DependencyFailureException}), the application's idempotency and lock failures and any adopter
|
||||
* carrier — through its own {@link ApiErrorCode}. One branch, so the web adapter answers a
|
||||
* carrier exactly as the GraphQL, gRPC and STOMP adapters do. A carrier wrapped in another
|
||||
* exception is found in the cause chain ({@link ApiErrorCarrier#firstIn}) and answers the same
|
||||
* way (review 2026-11-06 RR7-01-05).
|
||||
*
|
||||
* <p>What reaches the log is {@link ServerFailureLog}'s line, the one the GraphQL and gRPC
|
||||
* adapters write too: a persistence carrier by its classification only (its cause can hold SQL
|
||||
@@ -166,9 +171,10 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
* incident. The span gets the same failure, a persistence one again reduced to its
|
||||
* classification. A retryable code with a registered delay also carries {@code Retry-After}.
|
||||
*
|
||||
* @param failure a throwable that implements {@link ApiErrorCarrier}
|
||||
* @param failure a throwable that implements {@link ApiErrorCarrier} — the carrier itself, not a
|
||||
* wrapper around it, so its type decides what reaches the log
|
||||
*/
|
||||
public ResponseEntity<Envelope<Void>> handleCarrier(Exception failure) {
|
||||
public ResponseEntity<Envelope<Void>> handleCarrier(Throwable failure) {
|
||||
ApiErrorCode code = ((ApiErrorCarrier) failure).errorCode();
|
||||
ServerFailureLog.of(failure, code)
|
||||
.ifPresent(
|
||||
@@ -194,8 +200,9 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<Envelope<Void>> handleUnknown(Exception ex, WebRequest req) {
|
||||
if (ex instanceof ApiErrorCarrier) {
|
||||
return handleCarrier(ex);
|
||||
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(ex);
|
||||
if (carrier.isPresent()) {
|
||||
return handleCarrier(carrier.get());
|
||||
}
|
||||
log.error("unhandled exception on {}", req.getDescription(false), ex);
|
||||
spanErrorRecorder.recordException(ex, OperationalError.INTERNAL_ERROR.code());
|
||||
|
||||
+3
-1
@@ -33,7 +33,9 @@ public final class RetryAfterAdvisor {
|
||||
"DEPENDENCY_5XX_SERVER",
|
||||
2,
|
||||
"DEPENDENCY_CIRCUIT_OPEN",
|
||||
10);
|
||||
10,
|
||||
"LOCK_ACQUISITION_TIMEOUT",
|
||||
1);
|
||||
|
||||
private RetryAfterAdvisor() {}
|
||||
|
||||
|
||||
+101
@@ -10,6 +10,7 @@ import ch.qos.logback.core.read.ListAppender;
|
||||
import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedException;
|
||||
import dev.caskeleton.adapter.inbound.web.http.ApiHeaders;
|
||||
import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException;
|
||||
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
||||
import dev.caskeleton.shared.error.AdapterDisabledException;
|
||||
import dev.caskeleton.shared.error.Category;
|
||||
import dev.caskeleton.shared.error.ClientErrorMessages;
|
||||
@@ -26,6 +27,7 @@ import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.metadata.ConstraintDescriptor;
|
||||
import java.lang.reflect.Method;
|
||||
import java.sql.SQLException;
|
||||
import java.time.Duration;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
@@ -697,6 +699,105 @@ class GlobalExceptionHandlerTest {
|
||||
.isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aLockAcquisitionTimeoutIsAnsweredWithItsRetryableConflictAndTheRegisteredRetryAfter() {
|
||||
// when
|
||||
ResponseEntity<Envelope<Void>> response =
|
||||
handler.handleUnknown(
|
||||
new LockAcquisitionTimeoutException("orders/42", Duration.ofSeconds(3)),
|
||||
new ServletWebRequest(new MockHttpServletRequest("POST", "/orders/42")));
|
||||
|
||||
// then
|
||||
assertThat(response)
|
||||
.extracting(
|
||||
answer -> answer.getStatusCode().value(),
|
||||
answer -> answer.getBody().error().code(),
|
||||
answer -> answer.getBody().error().retryable(),
|
||||
answer -> answer.getHeaders().getFirst(ApiHeaders.RETRY_AFTER))
|
||||
.containsExactly(409, "LOCK_ACQUISITION_TIMEOUT", true, "1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCarrierWrappedInAnotherExceptionIsAnsweredWithItsOwnCode() {
|
||||
// given
|
||||
IllegalStateException wrapper =
|
||||
new IllegalStateException("use case failed", persistenceFailureWithASqlCause());
|
||||
|
||||
// when
|
||||
ResponseEntity<Envelope<Void>> response =
|
||||
handler.handleUnknown(
|
||||
wrapper, new ServletWebRequest(new MockHttpServletRequest("POST", "/work-logs")));
|
||||
|
||||
// then
|
||||
assertThat(response)
|
||||
.extracting(
|
||||
answer -> answer.getStatusCode().value(), answer -> answer.getBody().error().code())
|
||||
.containsExactly(503, "DB_UNAVAILABLE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrappedPersistenceFailureIsLoggedByItsClassificationWithoutTheWrapperOrTheSqlCause() {
|
||||
// given
|
||||
IllegalStateException wrapper =
|
||||
new IllegalStateException("use case failed", persistenceFailureWithASqlCause());
|
||||
|
||||
// when
|
||||
List<ILoggingEvent> logged =
|
||||
loggedWhile(
|
||||
() ->
|
||||
handler.handleUnknown(
|
||||
wrapper,
|
||||
new ServletWebRequest(new MockHttpServletRequest("POST", "/work-logs"))));
|
||||
|
||||
// then
|
||||
assertThat(logged)
|
||||
.singleElement()
|
||||
.extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy)
|
||||
.containsExactly(
|
||||
"persistence failure classified as DB_UNAVAILABLE (category=TRANSIENT_DEPENDENCY,"
|
||||
+ " retryable=true)",
|
||||
null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIllegalArgumentAroundACarrierIsAnsweredWithTheCarriersCode() {
|
||||
// given
|
||||
IllegalArgumentException wrapper =
|
||||
new IllegalArgumentException("bad request", persistenceFailureWithASqlCause());
|
||||
|
||||
// when
|
||||
ResponseEntity<Envelope<Void>> response = handler.handleIllegalArgument(wrapper);
|
||||
|
||||
// then
|
||||
assertThat(response)
|
||||
.extracting(
|
||||
answer -> answer.getStatusCode().value(), answer -> answer.getBody().error().code())
|
||||
.containsExactly(503, "DB_UNAVAILABLE");
|
||||
}
|
||||
|
||||
private static PersistenceFailureException persistenceFailureWithASqlCause() {
|
||||
return new PersistenceFailureException(
|
||||
OperationalError.DB_UNAVAILABLE,
|
||||
"persistence failure classified from SQLState=08006",
|
||||
new SQLException("jdbc:postgresql://db.internal/customer?password=secret", "08006"));
|
||||
}
|
||||
|
||||
/** Every line the handler writes while {@code action} runs. */
|
||||
private static List<ILoggingEvent> loggedWhile(Runnable action) {
|
||||
ch.qos.logback.classic.Logger logger =
|
||||
(ch.qos.logback.classic.Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
try {
|
||||
action.run();
|
||||
} finally {
|
||||
logger.detachAppender(appender);
|
||||
appender.stop();
|
||||
}
|
||||
return appender.list;
|
||||
}
|
||||
|
||||
private static MethodParameter validationProbeParameter() {
|
||||
try {
|
||||
Method method =
|
||||
|
||||
+7
@@ -96,4 +96,11 @@ class RetryAfterAdvisorTest {
|
||||
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.DEPENDENCY_CIRCUIT_OPEN))
|
||||
.hasValue(10);
|
||||
}
|
||||
|
||||
// docs/registries/error-codes.yaml LOCK_ACQUISITION_TIMEOUT row: retry_after_seconds 1.
|
||||
@Test
|
||||
void lockAcquisitionTimeoutHasRetryAfter1s() {
|
||||
assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.LOCK_ACQUISITION_TIMEOUT))
|
||||
.hasValue(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -98,8 +98,9 @@ WebSocket is a **build-composition opt-in**, not a dormant feature inside the de
|
||||
- Client `SEND` to `/topic/**` and other destinations is rejected.
|
||||
- Every client-visible processing failure becomes an ERROR frame with an empty payload and the
|
||||
fixed `message` `WEBSOCKET_REQUEST_REJECTED`. Its `error-code` header is the carried
|
||||
`ApiErrorCode` when an `ApiErrorCarrier` is in the cause chain, `BAD_PARAMETER` for an
|
||||
`IllegalArgumentException`, and `WEBSOCKET_REQUEST_REJECTED` otherwise.
|
||||
`ApiErrorCode` of the first `ApiErrorCarrier` in the cause chain (even behind an
|
||||
`IllegalArgumentException`), `BAD_PARAMETER` for an `IllegalArgumentException`, and
|
||||
`WEBSOCKET_REQUEST_REJECTED` otherwise.
|
||||
|
||||
## Event projection contract
|
||||
|
||||
|
||||
@@ -32,14 +32,23 @@
|
||||
클라이언트가 물러났다가(가능하면 다른 노드로) 다시 붙게 한다.
|
||||
- handler 메서드가 돌기 전의 처리 실패(inbound interceptor의 거부 등)는 빈 본문의 ERROR 프레임이 되고
|
||||
`message` 헤더는 고정값 `WEBSOCKET_REQUEST_REJECTED`다. `error-code` 헤더는 원인 사슬에
|
||||
`ApiErrorCarrier`가 있으면 그 코드, `IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는
|
||||
`WEBSOCKET_REQUEST_REJECTED`다.
|
||||
`ApiErrorCarrier`가 있으면 첫 carrier의 코드(`IllegalArgumentException` 뒤에 있어도),
|
||||
`IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는 `WEBSOCKET_REQUEST_REJECTED`다.
|
||||
- `@MessageMapping` 메서드의 실패는 inbound 채널 executor에서 끝나서 프레임이 나가지 않는다. 서버 로그는
|
||||
`StompHandlerFailureLog`가 web·GraphQL·gRPC와 같은 줄로 남긴다(`ServerFailureLog`): persistence 실패는
|
||||
분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. `IllegalArgumentException`은
|
||||
분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. 다른 예외로 감싼 carrier도 원인 사슬의
|
||||
첫 carrier로 같은 줄을 남긴다(재리뷰 RR7-01-05). `IllegalArgumentException`은
|
||||
`BAD_PARAMETER`로 보고 WARN 한 줄(`request refused as BAD_PARAMETER by <예외 타입>`)만 남긴다. 메시지는
|
||||
입력값이 들 수 있어 남기지 않는다. 그 밖의 예외는 예외와 함께 ERROR. 전에는 Spring이 예외 전체
|
||||
(persistence 실패의 SQL 원인 포함)를 ERROR로 남겼다.
|
||||
입력값이 들 수 있어 남기지 않는다.
|
||||
- handler가 돌기 전에 Spring이 클라이언트 메시지를 거부한 실패도 같은 모양 WARN 한 줄로 남긴다. 코드는 web이
|
||||
같은 실패에 답하는 코드다(재리뷰 RR7-01-06):
|
||||
- 읽지 못한 payload(`MessageConversionException`, 받은 메시지가 실린 것): `VALIDATION_FAILED`
|
||||
- 비었거나 검증에 걸린 payload(`MethodArgumentNotValidException`): `VALIDATION_FAILED`
|
||||
- `@DestinationVariable`·`@Header` 값이 파라미터 타입으로 바뀌지 않음(`ConversionFailedException`): `BAD_PARAMETER`
|
||||
|
||||
이 예외들의 메시지는 받은 JSON 조각이나 값을 담는다. 그래서 타입만 남긴다. 응답을 JSON으로 쓰지 못한
|
||||
`MessageConversionException`은 받은 메시지가 실리지 않는다. 서버 탓이라 ERROR로 남는다.
|
||||
- 그 밖의 예외는 예외와 함께 ERROR. 전에는 Spring이 예외 전체(persistence 실패의 SQL 원인 포함)를 ERROR로 남겼다.
|
||||
- `LiveEventProjector<T>` bean이 정확히 하나 있는 `@DomainEvent` 타입만 broadcast한다. 도메인
|
||||
객체를 그대로 직렬화하지 않고, projector가 만든 bounded `Map<String, String>`만 보낸다.
|
||||
|
||||
|
||||
+9
-6
@@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.websocket.stomp;
|
||||
|
||||
import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import java.util.Optional;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.simp.stomp.StompCommand;
|
||||
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
|
||||
@@ -14,9 +15,10 @@ import org.springframework.web.socket.messaging.StompSubProtocolErrorHandler;
|
||||
* <p>The frame's {@code message} header is fixed, so no exception text can reach the client. Its
|
||||
* {@code error-code} header is the stable code every other transport would send for the same
|
||||
* failure: an {@link ApiErrorCarrier} anywhere in the cause chain (Spring wraps a failure raised
|
||||
* while the frame is processed in a {@code MessagingException}) reports its own code, an {@link
|
||||
* IllegalArgumentException} reports {@code BAD_PARAMETER}, and everything else stays {@link
|
||||
* #SAFE_ERROR_CODE}.
|
||||
* while the frame is processed in a {@code MessagingException}) reports its own code — the first
|
||||
* one, found as every transport finds it ({@link ApiErrorCarrier#firstIn}), even behind an {@link
|
||||
* IllegalArgumentException} — then an {@link IllegalArgumentException} reports {@code
|
||||
* BAD_PARAMETER}, and everything else stays {@link #SAFE_ERROR_CODE}.
|
||||
*
|
||||
* <p>What reaches it is what fails before a handler method runs — an inbound interceptor's refusal,
|
||||
* on the thread that received the frame. A {@code @MessageMapping} method runs on the inbound
|
||||
@@ -42,13 +44,14 @@ final class SafeStompSubProtocolErrorHandler extends StompSubProtocolErrorHandle
|
||||
}
|
||||
|
||||
private static String errorCodeOf(Throwable failure) {
|
||||
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
|
||||
if (carrier.isPresent()) {
|
||||
return ((ApiErrorCarrier) carrier.get()).errorCode().code();
|
||||
}
|
||||
int depth = 0;
|
||||
for (Throwable cause = failure;
|
||||
cause != null && depth++ < MAX_CAUSE_DEPTH;
|
||||
cause = cause.getCause()) {
|
||||
if (cause instanceof ApiErrorCarrier carrier) {
|
||||
return carrier.errorCode().code();
|
||||
}
|
||||
if (cause instanceof IllegalArgumentException) {
|
||||
return OperationalError.BAD_PARAMETER.code();
|
||||
}
|
||||
|
||||
+57
-10
@@ -1,10 +1,19 @@
|
||||
package dev.caskeleton.adapter.inbound.websocket.stomp;
|
||||
|
||||
import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.ApiErrorCode;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import dev.caskeleton.shared.error.ServerFailureLog;
|
||||
import java.util.Optional;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.core.convert.ConversionFailedException;
|
||||
import org.springframework.core.convert.TypeDescriptor;
|
||||
import org.springframework.messaging.converter.MessageConversionException;
|
||||
import org.springframework.messaging.handler.annotation.DestinationVariable;
|
||||
import org.springframework.messaging.handler.annotation.Header;
|
||||
import org.springframework.messaging.handler.annotation.MessageExceptionHandler;
|
||||
import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
|
||||
/**
|
||||
@@ -15,14 +24,24 @@ import org.springframework.web.bind.annotation.ControllerAdvice;
|
||||
* SafeStompSubProtocolErrorHandler}, which only sees what fails before a handler runs (an
|
||||
* interceptor's refusal). Without a handler for it, Spring's method handler logs the whole
|
||||
* exception and stops: a persistence failure's SQL cause — values, constraint names, credentials —
|
||||
* went to the log, and a client-side refusal was logged as an error. With this advice a carrier
|
||||
* gets {@link ServerFailureLog}'s line (a persistence failure its classification only, a
|
||||
* client-side code nothing); an {@link IllegalArgumentException} is the {@code BAD_PARAMETER} every
|
||||
* transport makes of it and gets the WARN line naming its type, never its message, which may echo
|
||||
* input (review 2026-11-05 RR6-01-06); anything else is logged with its exception, as before. The
|
||||
* request id is on MDC ({@link WebSocketCorrelationInterceptor}). The client is answered as before:
|
||||
* a handler method that throws sends no frame. A feature's own {@code @MessageExceptionHandler}
|
||||
* still takes precedence over this one.
|
||||
* went to the log, and a client-side refusal was logged as an error. With this advice a carrier —
|
||||
* the failure itself or the first one in its cause chain, as on every transport (review 2026-11-06
|
||||
* RR7-01-05) — gets {@link ServerFailureLog}'s line (a persistence failure its classification only,
|
||||
* a client-side code nothing); an {@link IllegalArgumentException} is the {@code BAD_PARAMETER}
|
||||
* every transport makes of it and gets the WARN line naming its type, never its message, which may
|
||||
* echo input (review 2026-11-05 RR6-01-06); anything else is logged with its exception, as before.
|
||||
* The request id is on MDC ({@link WebSocketCorrelationInterceptor}). The client is answered as
|
||||
* before: a handler method that throws sends no frame. A feature's own
|
||||
* {@code @MessageExceptionHandler} still takes precedence over this one.
|
||||
*
|
||||
* <p>Spring's own refusals of a message the client got wrong are client failures too, and get the
|
||||
* same WARN line under the code the web adapter answers the same failure with (review 2026-11-06
|
||||
* RR7-01-06): a payload the converter could not read ({@code VALIDATION_FAILED}, like an unreadable
|
||||
* HTTP body), a payload that failed validation or was empty ({@code VALIDATION_FAILED}), and a
|
||||
* destination variable or header that does not convert to its parameter's type ({@code
|
||||
* BAD_PARAMETER}, like a path variable). Their messages quote the input, so they are not logged. A
|
||||
* reply the converter could not write is the server's failure: Spring raises the same {@link
|
||||
* MessageConversionException} for it, but without a failed message, and it stays an error.
|
||||
*/
|
||||
@ControllerAdvice
|
||||
class StompHandlerFailureLog {
|
||||
@@ -31,8 +50,9 @@ class StompHandlerFailureLog {
|
||||
|
||||
@MessageExceptionHandler
|
||||
void logFailure(Exception failure) {
|
||||
if (failure instanceof ApiErrorCarrier carrier) {
|
||||
ServerFailureLog.of(failure, carrier.errorCode())
|
||||
Optional<Throwable> carrier = ApiErrorCarrier.firstIn(failure);
|
||||
if (carrier.isPresent()) {
|
||||
ServerFailureLog.of(carrier.get(), ((ApiErrorCarrier) carrier.get()).errorCode())
|
||||
.ifPresent(line -> log.error(line.format(""), line.arguments()));
|
||||
return;
|
||||
}
|
||||
@@ -41,6 +61,33 @@ class StompHandlerFailureLog {
|
||||
log.warn(line.format(""), line.arguments());
|
||||
return;
|
||||
}
|
||||
Optional<ApiErrorCode> refusal = clientRefusalOf(failure);
|
||||
if (refusal.isPresent()) {
|
||||
ServerFailureLog line = ServerFailureLog.refused(refusal.get(), failure);
|
||||
log.warn(line.format(""), line.arguments());
|
||||
return;
|
||||
}
|
||||
log.error("unhandled failure in a STOMP message handler", failure);
|
||||
}
|
||||
|
||||
/** The client-side code of a message Spring refused before the handler ran, if it is one. */
|
||||
private static Optional<ApiErrorCode> clientRefusalOf(Exception failure) {
|
||||
if (failure instanceof MessageConversionException conversion
|
||||
&& conversion.getFailedMessage() != null) {
|
||||
return Optional.of(OperationalError.VALIDATION_FAILED);
|
||||
}
|
||||
if (failure instanceof MethodArgumentNotValidException) {
|
||||
return Optional.of(OperationalError.VALIDATION_FAILED);
|
||||
}
|
||||
if (failure instanceof ConversionFailedException conversion
|
||||
&& isBoundFromTheMessage(conversion.getTargetType())) {
|
||||
return Optional.of(OperationalError.BAD_PARAMETER);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
/** Whether a conversion was into a handler parameter the client's destination or header fills. */
|
||||
private static boolean isBoundFromTheMessage(TypeDescriptor target) {
|
||||
return target.hasAnnotation(DestinationVariable.class) || target.hasAnnotation(Header.class);
|
||||
}
|
||||
}
|
||||
|
||||
+17
@@ -46,6 +46,23 @@ class SafeStompSubProtocolErrorHandlerTest {
|
||||
.containsExactly("MAPPING_FAILED", SafeStompSubProtocolErrorHandler.SAFE_ERROR_CODE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIllegalArgumentAroundACarrierReportsTheCarriersCode() {
|
||||
// given
|
||||
Throwable failure =
|
||||
new MessagingException(
|
||||
"SECRET_SENTINEL",
|
||||
new IllegalArgumentException(
|
||||
"SECRET_SENTINEL", new MappingException("SECRET_SENTINEL mapping detail")));
|
||||
|
||||
// when
|
||||
Message<byte[]> result = handler.handleClientMessageProcessingError(null, failure);
|
||||
|
||||
// then
|
||||
assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code"))
|
||||
.isEqualTo("MAPPING_FAILED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void anIllegalArgumentReportsBadParameter() {
|
||||
// when
|
||||
|
||||
+161
-4
@@ -10,14 +10,31 @@ import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.ApiErrorCode;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import dev.caskeleton.shared.error.PersistenceFailureException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.sql.SQLException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Stream;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.Arguments;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.support.StaticApplicationContext;
|
||||
import org.springframework.messaging.Message;
|
||||
import org.springframework.messaging.converter.ByteArrayMessageConverter;
|
||||
import org.springframework.messaging.converter.CompositeMessageConverter;
|
||||
import org.springframework.messaging.converter.JacksonJsonMessageConverter;
|
||||
import org.springframework.messaging.converter.MessageConversionException;
|
||||
import org.springframework.messaging.converter.MessageConverter;
|
||||
import org.springframework.messaging.converter.StringMessageConverter;
|
||||
import org.springframework.messaging.handler.annotation.DestinationVariable;
|
||||
import org.springframework.messaging.handler.annotation.Header;
|
||||
import org.springframework.messaging.handler.annotation.MessageMapping;
|
||||
import org.springframework.messaging.handler.annotation.Payload;
|
||||
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
|
||||
import org.springframework.messaging.simp.SimpMessageType;
|
||||
import org.springframework.messaging.simp.SimpMessagingTemplate;
|
||||
@@ -114,25 +131,123 @@ class StompHandlerFailureLogTest {
|
||||
IllegalStateException.class.getName());
|
||||
}
|
||||
|
||||
/** Messages a client gets wrong before the handler method runs: Spring refuses the argument. */
|
||||
static Stream<Arguments> clientArgumentRefusals() {
|
||||
return Stream.of(
|
||||
Arguments.of(
|
||||
"/app/greeting",
|
||||
"{\"name\": \"alice@example.com".getBytes(StandardCharsets.UTF_8),
|
||||
Map.of(),
|
||||
"VALIDATION_FAILED",
|
||||
"org.springframework.messaging.converter.MessageConversionException"),
|
||||
Arguments.of(
|
||||
"/app/greeting",
|
||||
new byte[0],
|
||||
Map.of(),
|
||||
"VALIDATION_FAILED",
|
||||
"org.springframework.messaging.handler.annotation.support"
|
||||
+ ".MethodArgumentNotValidException"),
|
||||
Arguments.of(
|
||||
"/app/orders/alice@example.com",
|
||||
new byte[0],
|
||||
Map.of(),
|
||||
"BAD_PARAMETER",
|
||||
"org.springframework.core.convert.ConversionFailedException"),
|
||||
Arguments.of(
|
||||
"/app/count",
|
||||
new byte[0],
|
||||
Map.of("count", "alice@example.com"),
|
||||
"BAD_PARAMETER",
|
||||
"org.springframework.core.convert.ConversionFailedException"));
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@MethodSource("clientArgumentRefusals")
|
||||
@DisplayName("읽을 수 없거나 검증에 걸린 payload, 변환할 수 없는 destination 변수·header는 WARN 한 줄(타입만)로 남는다")
|
||||
void aClientArgumentRefusalIsLoggedAtWarnByItsTypeWithoutItsMessage(
|
||||
String destination,
|
||||
byte[] payload,
|
||||
Map<String, Object> headers,
|
||||
String code,
|
||||
String failureType) {
|
||||
// when
|
||||
List<ILoggingEvent> logged = loggedWhileHandling(destination, payload, headers);
|
||||
|
||||
// then
|
||||
assertThat(logged)
|
||||
.singleElement()
|
||||
.extracting(
|
||||
ILoggingEvent::getLevel,
|
||||
ILoggingEvent::getFormattedMessage,
|
||||
ILoggingEvent::getThrowableProxy)
|
||||
.containsExactly(Level.WARN, "request refused as " + code + " by " + failureType, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aReplyTheConverterCannotWriteIsLoggedAtErrorWithTheFailure() {
|
||||
// when
|
||||
List<ILoggingEvent> logged = loggedWhileHandling("/app/unwritable-reply");
|
||||
|
||||
// then
|
||||
assertThat(logged)
|
||||
.singleElement()
|
||||
.extracting(
|
||||
ILoggingEvent::getLevel,
|
||||
ILoggingEvent::getFormattedMessage,
|
||||
event -> event.getThrowableProxy().getClassName())
|
||||
.containsExactly(
|
||||
Level.ERROR,
|
||||
"unhandled failure in a STOMP message handler",
|
||||
MessageConversionException.class.getName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aWrappedPersistenceFailureIsLoggedByItsClassificationWithoutTheWrapperOrTheSqlCause() {
|
||||
// when
|
||||
List<ILoggingEvent> logged = loggedWhileHandling("/app/wrapped-persistence");
|
||||
|
||||
// then
|
||||
assertThat(logged)
|
||||
.singleElement()
|
||||
.extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy)
|
||||
.containsExactly(
|
||||
"persistence failure classified as DB_UNAVAILABLE (category=TRANSIENT_DEPENDENCY,"
|
||||
+ " retryable=true)",
|
||||
null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every ERROR or WARN line written anywhere while one message to {@code destination} is handled.
|
||||
*/
|
||||
private static List<ILoggingEvent> loggedWhileHandling(String destination) {
|
||||
return loggedWhileHandling(destination, new byte[0], Map.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* Every ERROR or WARN line written anywhere while one message to {@code destination}, carrying
|
||||
* {@code payload} and {@code headers}, is handled.
|
||||
*/
|
||||
private static List<ILoggingEvent> loggedWhileHandling(
|
||||
String destination, byte[] payload, Map<String, Object> headers) {
|
||||
StaticApplicationContext context = new StaticApplicationContext();
|
||||
context.registerSingleton("failingController", FailingController.class);
|
||||
context.registerSingleton("stompHandlerFailureLog", StompHandlerFailureLog.class);
|
||||
context.refresh();
|
||||
// The handler @EnableWebSocketMessageBroker wires; it is the one that reads @ControllerAdvice.
|
||||
// The converters @EnableWebSocketMessageBroker gives the handler and the broker template.
|
||||
SimpMessagingTemplate brokerTemplate =
|
||||
new SimpMessagingTemplate(new ExecutorSubscribableChannel());
|
||||
brokerTemplate.setMessageConverter(brokerMessageConverter());
|
||||
WebSocketAnnotationMethodMessageHandler handler =
|
||||
new WebSocketAnnotationMethodMessageHandler(
|
||||
new ExecutorSubscribableChannel(),
|
||||
new ExecutorSubscribableChannel(),
|
||||
new SimpMessagingTemplate(new ExecutorSubscribableChannel()));
|
||||
new ExecutorSubscribableChannel(), new ExecutorSubscribableChannel(), brokerTemplate);
|
||||
handler.setMessageConverter(brokerMessageConverter());
|
||||
handler.setDestinationPrefixes(List.of("/app"));
|
||||
handler.setApplicationContext(context);
|
||||
handler.afterPropertiesSet();
|
||||
Message<byte[]> message =
|
||||
MessageBuilder.withPayload(new byte[0])
|
||||
MessageBuilder.withPayload(payload)
|
||||
.copyHeaders(headers)
|
||||
.setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE)
|
||||
.setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, destination)
|
||||
.setHeader(SimpMessageHeaderAccessor.SESSION_ID_HEADER, "session-1")
|
||||
@@ -155,6 +270,14 @@ class StompHandlerFailureLogTest {
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static MessageConverter brokerMessageConverter() {
|
||||
return new CompositeMessageConverter(
|
||||
List.of(
|
||||
new StringMessageConverter(),
|
||||
new ByteArrayMessageConverter(),
|
||||
new JacksonJsonMessageConverter()));
|
||||
}
|
||||
|
||||
/** A feature's STOMP controller whose use case fails in each of the ways that matter. */
|
||||
@Controller
|
||||
static class FailingController {
|
||||
@@ -188,6 +311,40 @@ class StompHandlerFailureLogTest {
|
||||
void unrecognised() {
|
||||
throw new IllegalStateException("boom");
|
||||
}
|
||||
|
||||
@MessageMapping("/greeting")
|
||||
void greeting(@Payload Greeting greeting) {}
|
||||
|
||||
@MessageMapping("/orders/{id}")
|
||||
void order(@DestinationVariable UUID id) {}
|
||||
|
||||
@MessageMapping("/count")
|
||||
void count(@Header("count") int count) {}
|
||||
|
||||
@MessageMapping("/unwritable-reply")
|
||||
UnwritableReply unwritableReply() {
|
||||
return new UnwritableReply();
|
||||
}
|
||||
|
||||
@MessageMapping("/wrapped-persistence")
|
||||
void wrappedPersistence() {
|
||||
throw new IllegalStateException(
|
||||
"use case failed",
|
||||
new PersistenceFailureException(
|
||||
OperationalError.DB_UNAVAILABLE,
|
||||
"08006",
|
||||
new SQLException("jdbc:postgresql://db.internal/customer?password=secret", "08006")));
|
||||
}
|
||||
}
|
||||
|
||||
/** A payload a client sends as JSON. */
|
||||
record Greeting(String name) {}
|
||||
|
||||
/** A reply the JSON converter cannot write: its only property is itself. */
|
||||
static final class UnwritableReply {
|
||||
public UnwritableReply getSelf() {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
/** A use-case failure carrying a shared code. */
|
||||
|
||||
+11
@@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.application.lock.LockAcquisitionTimeoutException;
|
||||
import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources;
|
||||
import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.Category;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import java.io.InputStream;
|
||||
@@ -90,6 +91,16 @@ class LockAcquisitionTimeoutClassificationContractTest {
|
||||
.isEqualTo(OperationalError.LOCK_ACQUISITION_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* The code reaches a client only through {@link ApiErrorCarrier}: every transport reads a
|
||||
* failure's code from that hook and answers anything else as {@code INTERNAL_ERROR}.
|
||||
*/
|
||||
@Test
|
||||
void lockAcquisitionTimeoutExceptionIsTheCarrierTransportsReadTheCodeFrom() {
|
||||
assertThat(new LockAcquisitionTimeoutException("test-key", Duration.ofSeconds(3)))
|
||||
.isInstanceOf(ApiErrorCarrier.class);
|
||||
}
|
||||
|
||||
// ---- registry-row leg -----------------------------------------------------
|
||||
|
||||
@Tag("document-contract")
|
||||
|
||||
@@ -577,8 +577,10 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt
|
||||
- `OperationalError.LOCK_ACQUISITION_TIMEOUT`(CONFLICT, 409, retryable=true)을 운반한다. 락
|
||||
경합은 일시적이다 — 현재 보유자가 임계 구역을 떠나거나 lease TTL 이 만료되면 재시도가
|
||||
획득한다(D6 효율 락).
|
||||
- web adapter 가 `errorCode()` + 고정 client-safe 메시지로 409 를 만든다. 진단용 `getMessage()`
|
||||
(key·waitTime 포함)는 서버 로그 전용이고 API 클라이언트에 전달하면 안 된다.
|
||||
- `ApiErrorCarrier` 를 구현한다. 그래서 전송이 따로 처리기를 두지 않아도 web 은 409 +
|
||||
`Retry-After: 1`(레지스트리 값), GraphQL·gRPC 는 같은 코드로 답하고, 4xx 라 서버 로그를 남기지 않는다. 전에는
|
||||
carrier 가 아니어서 모든 전송이 500 `INTERNAL_ERROR`(재시도 불가)와 "unhandled" ERROR 로 답했다(재리뷰
|
||||
RR7-01-04). 진단용 `getMessage()`(key·waitTime 포함)는 서버 로그 전용이고 API 클라이언트에 전달하면 안 된다.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+9
-4
@@ -1,16 +1,20 @@
|
||||
package dev.caskeleton.application.lock;
|
||||
|
||||
import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import java.time.Duration;
|
||||
|
||||
/**
|
||||
* Thrown by {@link DistributedLockPort#tryAcquire(String, Duration, Duration)} when the lock could
|
||||
* not be acquired within the bounded {@code waitTime}. Carries {@link
|
||||
* OperationalError#LOCK_ACQUISITION_TIMEOUT} (CONFLICT, 409, retryable — contention is transient).
|
||||
* The web adapter maps it to 409 with a client-safe message; {@link #getMessage()} is
|
||||
* server-log-only. See README.
|
||||
* OperationalError#LOCK_ACQUISITION_TIMEOUT} (CONFLICT, 409, retryable — contention is transient)
|
||||
* through {@link ApiErrorCarrier}, the hook every inbound transport reads a code from: the web
|
||||
* adapter answers 409 with {@code Retry-After}, GraphQL and gRPC the same code, and none of them
|
||||
* logs it as an unhandled failure. Without the hook it was answered as a 500 {@code INTERNAL_ERROR}
|
||||
* (review 2026-11-06 RR7-01-04). {@link #getMessage()} is server-log-only. See README.
|
||||
*/
|
||||
public final class LockAcquisitionTimeoutException extends RuntimeException {
|
||||
public final class LockAcquisitionTimeoutException extends RuntimeException
|
||||
implements ApiErrorCarrier {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@@ -41,6 +45,7 @@ public final class LockAcquisitionTimeoutException extends RuntimeException {
|
||||
* Returns {@link OperationalError#LOCK_ACQUISITION_TIMEOUT}, the stable client-facing error code
|
||||
* for a distributed-lock timeout.
|
||||
*/
|
||||
@Override
|
||||
public OperationalError errorCode() {
|
||||
return OperationalError.LOCK_ACQUISITION_TIMEOUT;
|
||||
}
|
||||
|
||||
+7
@@ -2,6 +2,7 @@ package dev.caskeleton.application.lock;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import dev.caskeleton.shared.error.ApiErrorCarrier;
|
||||
import dev.caskeleton.shared.error.OperationalError;
|
||||
import java.time.Duration;
|
||||
import org.junit.jupiter.api.Test;
|
||||
@@ -25,6 +26,12 @@ class LockAcquisitionTimeoutExceptionTest {
|
||||
assertThat(ex.errorCode()).isEqualTo(OperationalError.LOCK_ACQUISITION_TIMEOUT);
|
||||
}
|
||||
|
||||
@Test
|
||||
void isAnApiErrorCarrier() {
|
||||
assertThat(new LockAcquisitionTimeoutException("orders/42", Duration.ofSeconds(3)))
|
||||
.isInstanceOf(ApiErrorCarrier.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
void messageContainsKey() {
|
||||
LockAcquisitionTimeoutException ex =
|
||||
|
||||
@@ -79,7 +79,13 @@ Spring/Lettuce 타입을 노출하지 않는다.
|
||||
`PersistenceFailureException`, `DependencyFailureException`)와 application 멱등성 예외는 모두
|
||||
`ApiErrorCarrier` 를 구현한다. web·GraphQL·gRPC·STOMP 어댑터는 carrier 분기 하나로 매핑하므로
|
||||
타입별 handler 를 따로 두지 않는다. `IllegalArgumentException` 은 모든 전송에서 `BAD_PARAMETER`
|
||||
(400 / GraphQL `REQUEST` / gRPC `INVALID_ARGUMENT`)다.
|
||||
(400 / GraphQL `REQUEST` / gRPC `INVALID_ARGUMENT`)다. application 분산 락 timeout
|
||||
(`LockAcquisitionTimeoutException` → `LOCK_ACQUISITION_TIMEOUT`)도 carrier 다(재리뷰 RR7-01-04 전에는
|
||||
carrier 가 아니어서 모든 전송이 `INTERNAL_ERROR` 로 답했다).
|
||||
- 전송은 실패 자신만 보지 않고 원인 사슬의 첫 carrier 를 본다(`ApiErrorCarrier.firstIn`). use case나
|
||||
adapter가 carrier를 다른 예외로 감싸 던져도 네 전송 모두 그 carrier의 코드로 답한다. 전에는 gRPC만 사슬을
|
||||
따라가고 web·GraphQL·STOMP는 500 `INTERNAL_ERROR`로 답했다(소유자 결정 2026-11-06, 재리뷰 RR7-01-05).
|
||||
사슬이 자기 자신으로 돌아오면 거기서 멈춘다.
|
||||
|
||||
### ServerFailureLog — 모든 전송이 같은 로그 줄로
|
||||
- carrier로 답한 실패의 서버 로그 줄을 정한다. web·GraphQL·gRPC·STOMP 어댑터가 이 클래스 하나를 쓴다
|
||||
@@ -91,11 +97,16 @@ Spring/Lettuce 타입을 노출하지 않는다.
|
||||
사고가 아니다). `IDEMPOTENCY_RECOVERY_REQUIRED`는 예외 메시지 끝의 scope digest로 runbook이 기록을 찾는다.
|
||||
- 전송은 자기 상관 정보를 뒤에 붙인다: gRPC ` (method=<서비스/메서드>)`, GraphQL ` (executionId=<id>)`.
|
||||
예외는 늘 마지막 인자라 SLF4J가 예외로 받는다.
|
||||
- 로그 줄은 찾은 carrier 의 타입으로 정한다. 감싼 persistence 실패도 감싼 예외나 SQL 원인 없이 분류 한 줄만 남는다.
|
||||
- `IllegalArgumentException`을 `BAD_PARAMETER`로 답하면 네 전송 모두 `refusedArgument`의 WARN 한 줄
|
||||
`request refused as BAD_PARAMETER by <예외 타입>`을 남긴다. 사고가 아니라 잘못된 요청이라 ERROR가 아니고,
|
||||
사실은 서버 조립 실수(`IllegalStateException`이어야 할 것)인 400도 흔적이 남도록 타입은 적는다. 메시지는
|
||||
입력값이 들 수 있어 남기지 않고 예외도 붙이지 않는다(재리뷰 RR6-01-06 전에는 web만 이 줄을 남기고 STOMP는
|
||||
ERROR에 메시지까지 남겼다).
|
||||
- 그 밖에 전송이 클라이언트 탓으로 알아보는 실패는 `refused(code, failure)`의 같은 모양 WARN 한 줄
|
||||
`request refused as <code> by <예외 타입>`을 남긴다. code는 web이 같은 실패에 답하는 4xx 코드다. 지금은 STOMP가
|
||||
읽지 못한 payload·검증 실패를 `VALIDATION_FAILED`로, 변환되지 않는 destination 변수·header를
|
||||
`BAD_PARAMETER`로 남긴다(재리뷰 RR7-01-06).
|
||||
|
||||
### OperationalError (enum)
|
||||
스켈레톤 공통 운영/전송/보안 에러 코드의 집합이다. `USER_NOT_FOUND` 같은 **도메인 전용 코드는
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
package dev.caskeleton.shared.error;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.IdentityHashMap;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Transport-agnostic hook a throwable implements so a single inbound-adapter error handler can map
|
||||
* it to a protocol status without the skeleton naming the feature. The throwable carries a stable
|
||||
@@ -20,4 +25,28 @@ public interface ApiErrorCarrier {
|
||||
|
||||
/** The classified, client-facing operational code surfaced on the protocol status. */
|
||||
ApiErrorCode errorCode();
|
||||
|
||||
/**
|
||||
* The first carrier in {@code failure}'s cause chain — {@code failure} itself when it is one.
|
||||
*
|
||||
* <p>Every transport finds a failure's code through this, so a carrier that a use case or an
|
||||
* adapter wrapped in another exception answers with its own code on web, GraphQL, gRPC and STOMP
|
||||
* alike, instead of {@code INTERNAL_ERROR} on some of them (review 2026-11-06 RR7-01-05). The
|
||||
* search stops where a cause chain loops back on itself.
|
||||
*
|
||||
* @param failure the failure a transport is answering; may be {@code null}
|
||||
* @return the carrier as the throwable it is — hand that to {@link ServerFailureLog#of}, not the
|
||||
* wrapper, so its type still decides what may be logged
|
||||
*/
|
||||
static Optional<Throwable> firstIn(Throwable failure) {
|
||||
Set<Throwable> seen = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
for (Throwable current = failure;
|
||||
current != null && seen.add(current);
|
||||
current = current.getCause()) {
|
||||
if (current instanceof ApiErrorCarrier) {
|
||||
return Optional.of(current);
|
||||
}
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
+20
-2
@@ -30,7 +30,12 @@ import java.util.Optional;
|
||||
*
|
||||
* <p>One line is not an error: {@link #refusedArgument(IllegalArgumentException)}, which every
|
||||
* transport writes at WARN when it answers an {@link IllegalArgumentException} as {@link
|
||||
* OperationalError#BAD_PARAMETER}.
|
||||
* OperationalError#BAD_PARAMETER}, and {@link #refused(ApiErrorCode, Throwable)} for the other
|
||||
* client failures a transport recognises.
|
||||
*
|
||||
* <p>The failure handed to {@link #of} is the carrier itself. A transport finds it with {@link
|
||||
* ApiErrorCarrier#firstIn(Throwable)}, so a carrier wrapped in another exception is logged by its
|
||||
* own type — a wrapped persistence failure still by its classification only.
|
||||
*/
|
||||
public final class ServerFailureLog {
|
||||
|
||||
@@ -89,8 +94,21 @@ public final class ServerFailureLog {
|
||||
* @param failure the refused argument; a carrier is logged by {@link #of} instead
|
||||
*/
|
||||
public static ServerFailureLog refusedArgument(IllegalArgumentException failure) {
|
||||
return refused(OperationalError.BAD_PARAMETER, failure);
|
||||
}
|
||||
|
||||
/**
|
||||
* The WARN line for any other failure a transport reads as the client's — a payload it could not
|
||||
* read, an argument that failed validation — classified as the client-side {@code code} the web
|
||||
* adapter answers the same failure with. It has {@link #refusedArgument}'s shape: the exception
|
||||
* type, never its message (a parser's message quotes the input), nothing attached.
|
||||
*
|
||||
* @param code the client-side (4xx) code the failure is classified as
|
||||
* @param failure the refused request's failure
|
||||
*/
|
||||
public static ServerFailureLog refused(ApiErrorCode code, Throwable failure) {
|
||||
return new ServerFailureLog(
|
||||
"request refused as " + OperationalError.BAD_PARAMETER.code() + " by {}",
|
||||
"request refused as " + code.code() + " by {}",
|
||||
new Object[] {failure.getClass().getName()},
|
||||
null);
|
||||
}
|
||||
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package dev.caskeleton.shared.error;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class ApiErrorCarrierTest {
|
||||
|
||||
@Test
|
||||
void aCarrierIsItsOwnFirstCarrier() {
|
||||
// given
|
||||
MappingException carrier = new MappingException("mapping detail");
|
||||
|
||||
// when
|
||||
Optional<Throwable> found = ApiErrorCarrier.firstIn(carrier);
|
||||
|
||||
// then
|
||||
assertThat(found).containsSame(carrier);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theFirstCarrierBehindWrappersIsFoundAndNotAnOuterOne() {
|
||||
// given
|
||||
MappingException inner = new MappingException("inner");
|
||||
MappingException outer = new MappingException("outer", new IllegalStateException("x", inner));
|
||||
IllegalStateException wrapper = new IllegalStateException("use case failed", outer);
|
||||
|
||||
// when
|
||||
Optional<Throwable> found = ApiErrorCarrier.firstIn(wrapper);
|
||||
|
||||
// then
|
||||
assertThat(found).containsSame(outer);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aChainWithoutACarrierHasNone() {
|
||||
// given
|
||||
IllegalStateException failure =
|
||||
new IllegalStateException("x", new IllegalArgumentException("y"));
|
||||
|
||||
// when
|
||||
Optional<Throwable> found = ApiErrorCarrier.firstIn(failure);
|
||||
|
||||
// then
|
||||
assertThat(found).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void aCauseChainThatLoopsEndsTheSearch() {
|
||||
// given
|
||||
IllegalStateException first = new IllegalStateException("first");
|
||||
IllegalStateException second = new IllegalStateException("second", first);
|
||||
first.initCause(second);
|
||||
|
||||
// when
|
||||
Optional<Throwable> found = ApiErrorCarrier.firstIn(first);
|
||||
|
||||
// then
|
||||
assertThat(found).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noFailureHasNoCarrier() {
|
||||
assertThat(ApiErrorCarrier.firstIn(null)).isEmpty();
|
||||
}
|
||||
}
|
||||
+16
@@ -104,6 +104,22 @@ class ServerFailureLogTest {
|
||||
new Object[] {"java.lang.IllegalArgumentException", "orders.v1.Orders/Charge"});
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRefusalNamesItsCodeAndTheExceptionTypeWithoutItsMessage() {
|
||||
// given
|
||||
RuntimeException failure =
|
||||
new UnsupportedOperationException("Could not read JSON: {\"to\": \"alice@example.com");
|
||||
|
||||
// when
|
||||
ServerFailureLog line = ServerFailureLog.refused(OperationalError.VALIDATION_FAILED, failure);
|
||||
|
||||
// then
|
||||
assertThat(new Object[] {line.format(""), line.arguments()})
|
||||
.containsExactly(
|
||||
"request refused as VALIDATION_FAILED by {}",
|
||||
new Object[] {"java.lang.UnsupportedOperationException"});
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTransportsOwnFieldsGoBetweenTheClassificationAndTheAttachedFailure() {
|
||||
// given
|
||||
|
||||
Reference in New Issue
Block a user