Design and Implementation of BetterGateway for Centralized Error‑Code Management in Distributed Systems
This article describes the background, design, configuration, code implementation, and testing of BetterGateway—a Spring Cloud Alibaba‑based gateway that centralizes error‑code management using Nacos and dynamic refresh to enable fast, accurate exception tracing across micro‑services and third‑party interfaces.
1. Background
In large distributed environments, the increasing number of clusters and long call chains make it difficult to locate problems quickly using scattered error codes, leading to high coupling when each service manages its own codes.
2. Overview
BetterGateway intercepts every request at the gateway before it reaches the business cluster and again on the way back, enabling centralized error‑code management. Nacos is used as the configuration center to store error codes, with dynamic refresh (both Nacos‑based and file‑system‑based) to update codes without downtime.
3. Functionality
The gateway assembles a special error‑code format that encodes the service provider, functional module, and interface, ensuring uniqueness for both internal service calls (service‑name + code) and third‑party calls (URL + status code).
4. Design
4.1 Overall Design
BetterGateway is built on Spring Cloud Alibaba and supports local file configuration. The request flow is: client → gateway → downstream service → gateway → client. When a downstream service encounters an exception, it can either throw the exception to be handled globally or return a processed error code to the gateway.
4.2 Component Details
4.2.1 Configuration Files
Configuration files are stored in Nacos or the local file system. Example JSON for service providers:
[
{
"code":"01",
"name":"order-service",
"dataId":"order-service.json",
"domainName":"order-service",
"authMethod":"token",
"authConfig":{
"ignorePath":["/order/submit","/order/cancel"],
"ignorePathPrefix":["/common"]
},
"type":"inner",
"version":"5"
}
]Each provider includes fields such as code , name , dataId , domainName , authMethod , authConfig , type , and version .
Another example defines error‑code mappings:
[
{
"url":"order-service",
"featCode":"001",
"errorCodeList":[
{
"errorCode":"5106",
"code":"001",
"type":"P",
"tips":"当前用户无此节点操作权限",
"handleStrategy":"",
"handleParam":""
}
]
}
]4.2.2 Handling Strategies
distribute : forward to one or more target addresses.
forward : (currently unavailable) forward to a single address.
retry : (currently unavailable) retry with count and interval.
4.2.3 Custom Exception and Global Handler
Custom exception class APIException carries appCode , path , msg , and data . The global handler APIExceptionHandler catches this exception and returns a unified ApiResult object.
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class APIExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(APIExceptionHandler.class);
@ExceptionHandler(value = APIException.class)
public ApiResult
handleBizException(APIException e) {
logger.error("发生接口调用异常 原因是:", e);
ApiResult
result = new ApiResult<>(ResultCode.FAIL);
result.setAppCode(e.getAppCode());
result.setPath(e.getPath());
result.setMsg(e.getMsg());
result.setData(e.getData());
return result;
}
}4.3 Important Classes
CacheRequestBodyFilter : caches request bodies.
RemoveCachedBodyFilter : releases cached bodies.
GlobalExceptionHandler : processes non‑gateway and gateway exceptions.
ErrorCodeFilter / ErrorCodeSpringFilter : performs error‑code conversion.
AuthFilter : dynamic authentication per service provider.
4.4 Configuration Change Management
ConfigDataChangeContainer : stores the latest configuration.
CoreContainerService : compares and pulls new data.
NacosClient / FileClient : fetches configs from Nacos or local files.
NacosConfChangeHandler / FileConfigChangeHandler : listens for config changes.
5. Testing Scenarios
Four roles are involved: front‑end, gateway, sys‑service, api‑service, and third‑party interfaces. Various test cases demonstrate normal calls, internal exceptions, external interface failures, and situations where error‑code mappings are missing, showing how BetterGateway translates or forwards the original error codes.
5.1 Example Requests
http://localhost:81/sys/sysNormal – sys‑service returns normally.
http://localhost:81/sys/apiNormal – api‑service returns normally.
http://localhost:81/sys/sysException – sys‑service throws an exception, gateway converts the code.
http://localhost:81/sys/apiException – api‑service throws an exception, gateway converts the code.
http://localhost:81/sys/apiCallBaiduException – external third‑party call fails, gateway converts the code.
Same as above but without a configured mapping, the original error code is returned.
6. References
[1] BetterGateway overall design: https://www.processon.com/view/link/5fadea745653bb657c2f96e3
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.