0
# Block Request Handling
1
2
Customizable handlers for processing blocked requests, supporting JSON responses, HTML responses, and redirects with flexible callback management system.
3
4
## Capabilities
5
6
### BlockRequestHandler Interface
7
8
Functional interface for handling blocked requests in reactive Spring Cloud Gateway environment.
9
10
```java { .api }
11
/**
12
* Reactive handler for blocked requests
13
* Functional interface for custom block handling implementations
14
*/
15
@FunctionalInterface
16
public interface BlockRequestHandler {
17
/**
18
* Handle blocked request and return appropriate response
19
* @param exchange - Server web exchange for the blocked request
20
* @param t - Block exception that triggered the handling
21
* @return Mono<ServerResponse> representing the response to return
22
*/
23
Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t);
24
}
25
```
26
27
### DefaultBlockRequestHandler
28
29
Default implementation providing JSON and HTML error responses based on client Accept headers.
30
31
```java { .api }
32
/**
33
* Default implementation of BlockRequestHandler
34
* Provides JSON responses by default, HTML for browser requests
35
*/
36
public class DefaultBlockRequestHandler implements BlockRequestHandler {
37
/**
38
* Default constructor
39
*/
40
public DefaultBlockRequestHandler();
41
42
/**
43
* Handles blocked requests with content negotiation
44
* Returns JSON response (429) by default, HTML for browsers
45
* Uses Accept header to determine response type
46
* @param exchange - Server web exchange
47
* @param ex - Block exception
48
* @return Mono<ServerResponse> with appropriate content type (JSON or HTML)
49
*/
50
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex);
51
}
52
```
53
54
**Response Examples:**
55
56
JSON Response (default):
57
```json
58
{
59
"code": 429,
60
"message": "Blocked by Sentinel: FlowException"
61
}
62
```
63
64
HTML Response (for browsers):
65
```
66
Blocked by Sentinel: FlowException
67
```
68
69
### RedirectBlockRequestHandler
70
71
Block handler that redirects blocked requests to a specified URL.
72
73
```java { .api }
74
/**
75
* Block handler that redirects blocked requests to specified URL
76
* Useful for redirecting blocked users to maintenance or error pages
77
*/
78
public class RedirectBlockRequestHandler implements BlockRequestHandler {
79
/**
80
* Constructor with redirect URL
81
* @param url - URL to redirect blocked requests to
82
*/
83
public RedirectBlockRequestHandler(String url);
84
85
/**
86
* Handles blocked requests by redirecting to configured URL
87
* @param exchange - Server web exchange
88
* @param t - Block exception
89
* @return Mono<ServerResponse> with temporary redirect (302)
90
*/
91
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable t);
92
}
93
```
94
95
**Usage Examples:**
96
97
```java
98
// Redirect to maintenance page
99
BlockRequestHandler redirectHandler = new RedirectBlockRequestHandler("/maintenance.html");
100
GatewayCallbackManager.setBlockHandler(redirectHandler);
101
102
// Redirect to external error page
103
BlockRequestHandler externalRedirect = new RedirectBlockRequestHandler("https://example.com/blocked");
104
GatewayCallbackManager.setBlockHandler(externalRedirect);
105
```
106
107
### GatewayCallbackManager
108
109
Static manager for configuring block request handlers and request origin parsers.
110
111
```java { .api }
112
/**
113
* Manager for gateway callbacks including block handlers and origin parsers
114
* Provides static methods for configuration management
115
*/
116
public final class GatewayCallbackManager {
117
/**
118
* Gets current block request handler
119
* @return BlockRequestHandler current handler (never null)
120
*/
121
public static BlockRequestHandler getBlockHandler();
122
123
/**
124
* Sets custom block request handler
125
* @param blockHandler - Custom handler implementation (must not be null)
126
*/
127
public static void setBlockHandler(BlockRequestHandler blockHandler);
128
129
/**
130
* Resets block handler to default implementation
131
*/
132
public static void resetBlockHandler();
133
134
/**
135
* Gets current request origin parser function
136
* @return Function<ServerWebExchange, String> current parser (never null)
137
*/
138
public static Function<ServerWebExchange, String> getRequestOriginParser();
139
140
/**
141
* Sets custom request origin parser function
142
* @param requestOriginParser - Custom parser function (must not be null)
143
*/
144
public static void setRequestOriginParser(Function<ServerWebExchange, String> requestOriginParser);
145
146
/**
147
* Resets request origin parser to default implementation (returns empty string)
148
*/
149
public static void resetRequestOriginParser();
150
}
151
```
152
153
## Usage Patterns
154
155
### Custom JSON Response Handler
156
157
```java
158
public class CustomBlockRequestHandler implements BlockRequestHandler {
159
160
@Override
161
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
162
CustomErrorResponse error = new CustomErrorResponse(
163
"RATE_LIMIT_EXCEEDED",
164
"Too many requests. Please try again later.",
165
System.currentTimeMillis()
166
);
167
168
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
169
.contentType(MediaType.APPLICATION_JSON)
170
.body(fromObject(error));
171
}
172
173
private static class CustomErrorResponse {
174
private final String errorCode;
175
private final String message;
176
private final long timestamp;
177
178
// Constructor and getters...
179
}
180
}
181
182
// Configure custom handler
183
GatewayCallbackManager.setBlockHandler(new CustomBlockRequestHandler());
184
```
185
186
### Conditional Response Handler
187
188
```java
189
public class ConditionalBlockRequestHandler implements BlockRequestHandler {
190
191
@Override
192
public Mono<ServerResponse> handleRequest(ServerWebExchange exchange, Throwable ex) {
193
String path = exchange.getRequest().getPath().value();
194
195
if (path.startsWith("/api/")) {
196
// JSON response for API calls
197
return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
198
.contentType(MediaType.APPLICATION_JSON)
199
.body(fromObject(Map.of("error", "Rate limit exceeded")));
200
} else {
201
// Redirect for web pages
202
return ServerResponse.temporaryRedirect(URI.create("/blocked.html")).build();
203
}
204
}
205
}
206
```
207
208
### Custom Origin Parser
209
210
```java
211
// Extract origin from custom header
212
Function<ServerWebExchange, String> customOriginParser = exchange -> {
213
String customOrigin = exchange.getRequest().getHeaders().getFirst("X-Client-Origin");
214
if (customOrigin != null) {
215
return customOrigin;
216
}
217
218
// Fallback to IP address
219
InetSocketAddress remoteAddress = exchange.getRequest().getRemoteAddress();
220
return remoteAddress != null ? remoteAddress.getAddress().getHostAddress() : "unknown";
221
};
222
223
GatewayCallbackManager.setRequestOriginParser(customOriginParser);
224
```
225
226
### Configuration Management
227
228
```java
229
@Configuration
230
public class SentinelGatewayConfiguration {
231
232
@PostConstruct
233
public void configureSentinel() {
234
// Set custom block handler
235
GatewayCallbackManager.setBlockHandler(new CustomBlockRequestHandler());
236
237
// Set custom origin parser
238
GatewayCallbackManager.setRequestOriginParser(exchange -> {
239
return extractClientId(exchange);
240
});
241
}
242
243
private String extractClientId(ServerWebExchange exchange) {
244
// Custom client identification logic
245
String apiKey = exchange.getRequest().getHeaders().getFirst("API-Key");
246
return apiKey != null ? apiKey : "anonymous";
247
}
248
}
249
```
250
251
## Error Handling
252
253
### Exception Safety
254
- All handlers should handle exceptions gracefully to avoid disrupting the gateway
255
- Return appropriate error responses even when custom logic fails
256
- Use fallback responses for unexpected scenarios
257
258
### Response Status Codes
259
- **429 Too Many Requests**: Standard for rate limiting (recommended)
260
- **503 Service Unavailable**: For system protection scenarios
261
- **302 Found**: For redirect responses
262
- Custom status codes based on specific requirements
263
264
### Content Type Handling
265
- Respect client Accept headers when possible
266
- Provide JSON responses for API clients
267
- Provide HTML responses for browser clients
268
- Support custom content types as needed