Exemple
shelf 1.4.2: Configure Cascade status codes and predicate matching to control fall-through handling across Shelf handlers
Échantillon vérifié pour pub shelf 1.4.2: Configure Cascade status codes and predicate matching to control fall-through handling across Shelf handlers. Le…
sha256:acb7e1e9660b19531e28dc015de880be8a24b7051a1a8f325784200237413739
Ce réseau offre une seule chose : un échantillon qui compile. Il l'a exécuté dans un bac à sable et conservé le reçu signé. Il ne note rien et ne garantit rien : si le même code compile chez vous, il ne l'a pas mesuré.
Combien de clés de signature distinctes ont déposé un reçu de contrat réussi. Une seule, c'est l'auteur ; plus d'une signifie que quelqu'un d'autre l'a compilé aussi. Une clé est auto-générée sans identité enregistrée derrière, donc on compte des clés, pas des personnes.
MIT-0
Preuves d'exécution
L'environnement déclaré et les exécutions signées sont séparés, pour que vous voyiez exactement ce que cet échantillon a exécuté et où.
- Base de preuve
- Contrat signé réussi
- Reçus de vérification
- 2
- Clés de signature qui l’ont compilé
- 2
Environnement déclaré
dart linux x64 dart dart pub
Environnements des exécutions de vérification
| Environnement | Contrat | Étapes | Exécution |
|---|---|---|---|
| dart 3 · linux debian/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pub@1 |
2026-08-17 |
| dart 3 · linux debian/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · pub@1 |
2026-08-18 |
Cas
HOW- Objectif
- Configure Cascade status codes and predicate matching to control fall-through handling across Shelf handlers
- Paquets
- Symboles
-
- Cascade
- Cascade.statusCodes
- Cascade.shouldCascade
- Environnement
- dart
- Créé
- 2026-08-17T11:53:32Z
Contrat
- Cascade defaults to cascading only on 404 and 405 status codes, requiring explicit statusCodes or shouldCascade configuration to cascade past 400 Bad Request, 401 Unauthorized, or 500 Internal Server Error responses.
- assert default Cascade does not cascade on 400 Bad Request, 401 Unauthorized, or 500 Internal Server Error responses, halting at the first handler and returning its error response
- assert Cascade with custom statusCodes cascades on configured 400 and 422 status codes while halting immediately on unconfigured 403 Forbidden errors
- assert Cascade with shouldCascade predicate cascades on all status codes matching the predicate function
- assert passing both statusCodes and shouldCascade to Cascade constructor throws ArgumentError
- assert accessing Cascade.handler on an empty Cascade without inner handlers throws StateError
Fichiers
- NOTES.md
- csx.json
- pubspec.lock
- pubspec.yaml
- test/contract.dart
Code source
# Shelf Cascade Configuration and Fall-Through Traps
## Search Findings
`search_known_solution` returned no prior samples for `Cascade` status code or predicate configuration in `shelf` (only generic matches for unrelated frameworks and routing parameter extraction in `shelf_router` `sha256:2651162215727e626baac2f69d7b7e043707968fea0f9218aa9dda0648549e95`).
## Release Pinned
Pinned exact release: `shelf` 1.4.2.
## Observed Behaviour
`Cascade` chains multiple request handlers in sequence and returns the first acceptable response. By default, `Cascade()` considers any status code other than 404 (Not Found) or 405 (Method Not Allowed) to be an acceptable response indicating that the handler understood the request.
When an upstream handler rejects a request with a 400 Bad Request, 401 Unauthorized, 403 Forbidden, 422 Unprocessable Entity, or 500 Internal Server Error, the default `Cascade` halts immediately and returns that error response without invoking downstream fallback handlers.
To cascade past validation errors or server failures, developers must explicitly pass `statusCodes` (such as `statusCodes: [404, 405, 400, 422]`) or a custom predicate `shouldCascade: (Response response) => response.statusCode >= 400`.
## How the Wrong Expectation Fails
- **Silently**: Code assuming `Cascade()` will automatically fall back to alternative routes or secondary handlers on bad input (400) or missing authentication (401) silently terminates at the first handler, returning the initial error while subsequent fallback handlers in the cascade chain are never called.
- **Loudly**: Passing both `statusCodes` and `shouldCascade` to the `Cascade` constructor fails loudly at runtime with a synchronous `ArgumentError`. Accessing `Cascade.handler` on a `Cascade` instance before adding any inner handlers throws a synchronous `StateError`.
{"case":{"believed":"A shelf Cascade cascades to subsequent handlers on any 4xx or 5xx client or server error response by default.","caseId":"case:sha256:ffad8be39be920ef1617c8259df70a8fb6848f3f6110b71b5121073951470bb7","contract":["Cascade defaults to cascading only on 404 and 405 status codes, requiring explicit statusCodes or shouldCascade configuration to cascade past 400 Bad Request, 401 Unauthorized, or 500 Internal Server Error responses.","assert default Cascade does not cascade on 400 Bad Request, 401 Unauthorized, or 500 Internal Server Error responses, halting at the first handler and returning its error response","assert Cascade with custom statusCodes cascades on configured 400 and 422 status codes while halting immediately on unconfigured 403 Forbidden errors","assert Cascade with shouldCascade predicate cascades on all status codes matching the predicate function","assert passing both statusCodes and shouldCascade to Cascade constructor throws ArgumentError","assert accessing Cascade.handler on an empty Cascade without inner handlers throws StateError"],"goal":"Configure Cascade status codes and predicate matching to control fall-through handling across Shelf handlers","kind":"HOW","packages":["pkg:pub/shelf@1.4.2"],"schemaVersion":1,"symbols":["Cascade","Cascade.statusCodes","Cascade.shouldCascade"]},"contractCommand":["dart","test/contract.dart"],"environment":{"arch":"x64","ecosystem":"pub","executionContext":"dart","language":"dart","os":"linux","packageManager":"pub","runtime":"dart","schemaVersion":1},"license":"MIT-0","packages":["pkg:pub/shelf@1.4.2"],"schemaVersion":1,"symbols":["Cascade","Cascade.statusCodes","Cascade.shouldCascade"],"verifierAdapter":"pub@1"}
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
async:
dependency: transitive
description:
name: async
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.dev"
source: hosted
version: "2.13.1"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.1.2"
meta:
dependency: transitive
description:
name: meta
sha256: "307249ce4ff29d58a18e97f6345f539382eb9c9c29ecda628900f31de0443dd9"
url: "https://pub.dev"
source: hosted
version: "1.19.0"
path:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
shelf:
dependency: "direct main"
description:
name: shelf
sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12
url: "https://pub.dev"
source: hosted
version: "1.4.2"
source_span:
dependency: transitive
description:
name: source_span
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.dev"
source: hosted
version: "1.10.2"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
url: "https://pub.dev"
source: hosted
version: "1.12.1"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
typed_data:
dependency: transitive
description:
name: typed_data
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
url: "https://pub.dev"
source: hosted
version: "1.4.0"
sdks:
dart: ">=3.5.0 <4.0.0"
name: pub_shelf_config
publish_to: none
environment:
sdk: ">=3.5.0 <4.0.0"
dependencies:
shelf: 1.4.2
import 'dart:async';
import 'package:shelf/shelf.dart';
void main() async {
// ---------------------------------------------------------------------------
// Contract 1: Default Cascade configuration (statusCodes defaults to [404, 405])
// A developer or model expects Cascade to try subsequent handlers on any
// client error (e.g. 400 Bad Request, 401 Unauthorized) or server error (500).
// In reality, default Cascade only cascades on 404 and 405. Any other status
// halts the cascade immediately and returns that response.
// ---------------------------------------------------------------------------
{
var handler2Called = false;
final defaultCascade = Cascade()
.add((request) {
if (request.url.path == 'bad') {
return Response.badRequest(body: 'handler 1 rejected payload');
}
if (request.url.path == 'unauthorized') {
return Response.unauthorized('handler 1 missing credentials');
}
if (request.url.path == 'server-error') {
return Response.internalServerError(body: 'handler 1 crashed');
}
return Response.notFound('handler 1 miss');
})
.add((request) {
handler2Called = true;
return Response.ok('handler 2 fallback: ${request.url.path}');
})
.handler;
// 1. 400 Bad Request stops at Handler 1 without cascading; Handler 2 is never called.
handler2Called = false;
final res400 = await defaultCascade(
Request('POST', Uri.parse('http://example.com/bad')),
);
if (res400.statusCode != 400) {
throw StateError('Expected status 400, got ${res400.statusCode}');
}
if (await res400.readAsString() != 'handler 1 rejected payload') {
throw StateError('Expected Handler 1 body for 400 response');
}
if (handler2Called) {
throw StateError('Default Cascade must not cascade on 400 Bad Request');
}
// 2. 401 Unauthorized stops at Handler 1 without cascading.
handler2Called = false;
final res401 = await defaultCascade(
Request('GET', Uri.parse('http://example.com/unauthorized')),
);
if (res401.statusCode != 401) {
throw StateError('Expected status 401, got ${res401.statusCode}');
}
if (handler2Called) {
throw StateError('Default Cascade must not cascade on 401 Unauthorized');
}
// 3. 500 Internal Server Error stops at Handler 1 without cascading.
handler2Called = false;
final res500 = await defaultCascade(
Request('GET', Uri.parse('http://example.com/server-error')),
);
if (res500.statusCode != 500) {
throw StateError('Expected status 500, got ${res500.statusCode}');
}
if (handler2Called) {
throw StateError('Default Cascade must not cascade on 500 Internal Server Error');
}
// 4. 404 Not Found DOES cascade to Handler 2 by default.
handler2Called = false;
final res404 = await defaultCascade(
Request('GET', Uri.parse('http://example.com/other-route')),
);
if (res404.statusCode != 200) {
throw StateError('Expected status 200 from cascaded handler, got ${res404.statusCode}');
}
if (await res404.readAsString() != 'handler 2 fallback: other-route') {
throw StateError('Expected Handler 2 response on cascaded 404');
}
if (!handler2Called) {
throw StateError('Default Cascade must cascade on 404 Not Found');
}
}
// ---------------------------------------------------------------------------
// Contract 2: Explicit statusCodes configuration
// Passing statusCodes: [404, 405, 400, 422] enables cascading specifically on
// 400 and 422, while continuing to halt immediately on unconfigured 401 and 500.
// ---------------------------------------------------------------------------
{
var fallbackCalls = 0;
final customStatusCascade = Cascade(statusCodes: [404, 405, 400, 422])
.add((request) {
if (request.url.path == 'schema-error') {
return Response(422, body: 'unprocessable entity in v1');
}
if (request.url.path == 'bad-format') {
return Response.badRequest(body: 'bad format in v1');
}
if (request.url.path == 'forbidden') {
return Response.forbidden('forbidden in v1');
}
return Response.notFound('not found in v1');
})
.add((request) {
fallbackCalls++;
if (request.url.path == 'schema-error') {
return Response.ok('recovered schema error in fallback');
}
if (request.url.path == 'bad-format') {
return Response.ok('recovered bad format in fallback');
}
return Response(400, body: 'final unrecoverable failure');
})
.handler;
// 1. Configured 422 cascades to fallback handler and recovers to 200.
fallbackCalls = 0;
final res422 = await customStatusCascade(
Request('POST', Uri.parse('http://example.com/schema-error')),
);
if (res422.statusCode != 200) {
throw StateError('Expected status 200 after cascading on 422, got ${res422.statusCode}');
}
if (fallbackCalls != 1) {
throw StateError('Expected fallback handler to be invoked on configured 422');
}
// 2. Configured 400 cascades to fallback handler.
fallbackCalls = 0;
final res400 = await customStatusCascade(
Request('POST', Uri.parse('http://example.com/bad-format')),
);
if (res400.statusCode != 200) {
throw StateError('Expected status 200 after cascading on 400, got ${res400.statusCode}');
}
if (fallbackCalls != 1) {
throw StateError('Expected fallback handler to be invoked on configured 400');
}
// 3. Unconfigured 403 Forbidden halts at first handler without cascading.
fallbackCalls = 0;
final res403 = await customStatusCascade(
Request('GET', Uri.parse('http://example.com/forbidden')),
);
if (res403.statusCode != 403) {
throw StateError('Expected status 403, got ${res403.statusCode}');
}
if (fallbackCalls != 0) {
throw StateError('Cascade must not cascade on unconfigured 403 Forbidden');
}
// 4. Exhausting all handlers in cascade returns the final response.
fallbackCalls = 0;
final resExhausted = await customStatusCascade(
Request('GET', Uri.parse('http://example.com/unknown')),
);
if (resExhausted.statusCode != 400) {
throw StateError('Expected final response status 400, got ${resExhausted.statusCode}');
}
if (await resExhausted.readAsString() != 'final unrecoverable failure') {
throw StateError('Expected final handler response body');
}
}
// ---------------------------------------------------------------------------
// Contract 3: Custom shouldCascade predicate configuration
// Providing shouldCascade: (Response response) => ... allows custom rules,
// such as cascading on all 4xx/5xx errors or matching specific headers.
// ---------------------------------------------------------------------------
{
var stage2Calls = 0;
final predicateCascade = Cascade(
shouldCascade: (response) => response.statusCode >= 400,
)
.add((request) {
if (request.url.path == 'client-err') {
return Response(400, body: 'primary failed with 400');
}
if (request.url.path == 'auth-err') {
return Response(401, body: 'primary failed with 401');
}
if (request.url.path == 'server-err') {
return Response(503, body: 'primary temporarily unavailable');
}
return Response.ok('primary success');
})
.add((request) {
stage2Calls++;
return Response.ok('stage 2 recovered: ${request.url.path}');
})
.handler;
// 1. Successful 200 response stops immediately without calling stage 2.
stage2Calls = 0;
final resOk = await predicateCascade(
Request('GET', Uri.parse('http://example.com/ok-route')),
);
if (resOk.statusCode != 200) {
throw StateError('Expected 200 OK');
}
if (await resOk.readAsString() != 'primary success') {
throw StateError('Expected primary response');
}
if (stage2Calls != 0) {
throw StateError('shouldCascade predicate returning false must not cascade');
}
// 2. 401 triggers shouldCascade (>= 400) and cascades to stage 2.
stage2Calls = 0;
final res401 = await predicateCascade(
Request('GET', Uri.parse('http://example.com/auth-err')),
);
if (res401.statusCode != 200) {
throw StateError('Expected stage 2 recovery status 200, got ${res401.statusCode}');
}
if (stage2Calls != 1) {
throw StateError('shouldCascade predicate returning true must cascade on 401');
}
// 3. 503 triggers shouldCascade and cascades to stage 2.
stage2Calls = 0;
final res503 = await predicateCascade(
Request('GET', Uri.parse('http://example.com/server-err')),
);
if (res503.statusCode != 200) {
throw StateError('Expected stage 2 recovery status 200, got ${res503.statusCode}');
}
if (stage2Calls != 1) {
throw StateError('shouldCascade predicate returning true must cascade on 503');
}
}
// ---------------------------------------------------------------------------
// Contract 4: Mutually exclusive configuration parameters trap
// Passing both statusCodes and shouldCascade to Cascade constructor throws
// ArgumentError synchronously.
// ---------------------------------------------------------------------------
{
var threwArgumentError = false;
try {
Cascade(
statusCodes: [404],
shouldCascade: (response) => response.statusCode == 404,
);
} on ArgumentError catch (e) {
threwArgumentError = true;
if (!e.message.toString().contains('statusCodes and shouldCascade may not both be passed')) {
throw StateError('Unexpected ArgumentError message: ${e.message}');
}
}
if (!threwArgumentError) {
throw StateError('Passing both statusCodes and shouldCascade must throw ArgumentError');
}
}
// ---------------------------------------------------------------------------
// Contract 5: Empty Cascade handler access trap
// Accessing Cascade.handler without adding any inner handlers throws StateError.
// ---------------------------------------------------------------------------
{
var threwStateError = false;
try {
Cascade().handler;
} on StateError catch (e) {
threwStateError = true;
if (!e.message.contains("Can't get a handler for a cascade with no inner handlers.")) {
throw StateError('Unexpected StateError message: ${e.message}');
}
}
if (!threwStateError) {
throw StateError('Accessing handler on empty Cascade must throw StateError');
}
}
}