Customizing Block Exception Responses in Sentinel 1.8.0 for Spring MVC
In Sentinel 1.8.0 and later, the legacy WebCallbackManager and UrlBlockHandler interfaces have been phased out. Developers integrating Sentinel with Spring Boot must adopt the BlockExceptionHandler interface to define custom HTTP responses for traffic-rejected requests.
Implementing a Custom Handler
Register a Spring-managed component that implements BlockExceptionHandler. The framework automatically detects the bean and injects it into the request interception pipeline.
@Component
public class RateLimitResponseHandler implements BlockExceptionHandler {
private final ObjectMapper jsonMapper = new ObjectMapper();
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException exception) throws Exception {
response.setStatus(429);
response.setContentType("application/json; charset=utf-8");
Map<String, Object> errorPayload = new LinkedHashMap<>();
errorPayload.put("code", "RATE_LIMIT_EXCEEDED");
errorPayload.put("detail", "Traffic threshold breached. Retry after a cooldown period.");
errorPayload.put("traceId", System.currentTimeMillis());
jsonMapper.writeValue(response.getWriter(), errorPayload);
}
}
The resulting HTTP response follows this structure:
{"code":"RATE_LIMIT_EXCEEDED","detail":"Traffic threshold breached. Retry after a cooldown period.","traceId":1715203456789}
Common Configuration Pitfalls
Attempting to register a custom handler via WebMvcConfigurer.addInterceptors() or by direct assigning a property on SentinelWebMvcConfig will fail. The adapter configuration extends BaseWebMvcConfig, which deliberately omits a public setter for block handlers in this release. The interceptor chain relies on the Spring application context to resolve the BlockExceptionHandler bean automatically.
For reliable integration, rely on the auto-configuration provided by the sentinel-spring-webmvc-adapter dependency rather than manual interceptor registration or reflection-based field injection.