Spring Integration中Http REST端点异常处理:如何向用户抛出异常?
解决Spring Integration HTTP网关捕获404并抛自定义异常的方案
1. 自定义异常类
先创建用于传递给终端用户的自定义异常:
public class ApiNotFoundException extends RuntimeException { public ApiNotFoundException(String message) { super(message); } }
2. 调整ExpressionEvaluatingRequestHandlerAdvice配置
修改advice配置,开启异常传播,并调整失败处理逻辑:
<int-http:request-handler-advice-chain> <bean class="org.springframework.integration.handler.advice.ExpressionEvaluatingRequestHandlerAdvice"> <property name="successChannel" ref="afterSuccessFetchChannel" /> <!-- 方案一:失败通道+自定义处理器(适合复杂判断逻辑) --> <property name="failureChannel" ref="afterFailFetchChannel" /> <!-- 核心配置:允许失败通道的异常向上传播到终端用户 --> <property name="propagateEvaluationFailures" value="true" /> <!-- 方案二:直接用failureExpression抛异常(适合简单场景),可替换上面的failureChannel配置 --> <!-- <property name="failureExpression"> <value> #root.cause instanceof T(org.springframework.web.client.HttpClientErrorException) && #root.cause.statusCode == T(org.springframework.http.HttpStatus).NOT_FOUND ? T(com.example.ApiNotFoundException).new('Requested resource not found: ' + #root.cause.message) : T(java.lang.RuntimeException).new('Request failed: ' + #root.cause.message) </value> </property> --> </bean> </int-http:request-handler-advice-chain>
3. 实现失败异常处理器(方案一专用)
创建处理器类,解析失败消息中的HTTP异常,判断404后抛出自定义异常:
@Component("failureExceptionHandler") public class FailureExceptionHandler { public void handleFailure(MessageHandlingException exception) { Throwable rootCause = exception.getCause(); if (rootCause instanceof HttpClientErrorException) { HttpClientErrorException httpError = (HttpClientErrorException) rootCause; if (HttpStatus.NOT_FOUND.equals(httpError.getStatusCode())) { throw new ApiNotFoundException("Requested resource not found: " + httpError.getMessage()); } // 其他HTTP异常可按需转为对应自定义异常或直接抛出 throw new RuntimeException("API request failed with status " + httpError.getStatusCode(), httpError); } // 非HTTP异常统一处理 throw new RuntimeException("Request processing failed", exception); } }
4. 更新失败通道配置
替换原日志处理逻辑,用自定义处理器接管失败通道:
<!-- 移除原失败通道的transformer和日志适配器 --> <int:service-activator input-channel="afterFailFetchChannel" ref="failureExceptionHandler" method="handleFailure" /> <!-- 成功通道的日志处理保留不变 --> <int:transformer input-channel="afterSuccessFetchChannel" output-channel="goodResultChannel" expression="'Fetching load id: ' + payload + ' details was successful'" /> <int:logging-channel-adapter id="goodResultChannel" level="INFO" />
关键说明
propagateEvaluationFailures设为true是核心:默认情况下,失败通道处理抛出的异常会被advice吞掉,开启该配置后,异常会传播回原调用链路,最终抛给终端用户。- Spring Integration HTTP网关遇到4xx/5xx响应时,会抛出
HttpClientErrorException(4xx)或HttpServerErrorException(5xx),可通过getStatusCode()判断具体状态码。
内容的提问来源于stack exchange,提问作者KeepItSimple
相关产品推荐
相关产品推荐

