在Quarkus的Apache Camel中捕获特定Base64解码异常并抛出
解决方案
要捕获这个特定的Base64解码异常并返回自定义错误,你可以按以下步骤修改代码:
1. (可选但推荐)定义自定义异常
如果项目里还没有专门的Base64解码异常类,先创建一个,让全局异常处理器能更精准识别:
public class Base64DecodeException extends RuntimeException { public Base64DecodeException(String message) { super(message); } }
2. 修改异常捕获逻辑
在原代码的catch块中,针对通用Exception增加判断,识别目标异常消息后抛出自定义异常:
public class UserProfileProcessorUserIdParamReq implements Processor { private final IValidationFieldsUserID validationFields; public UserProfileProcessorUserIdParamReq() { validationFields = new ValidationFieldsUserID(); } @Override public void process(Exchange exchange) throws Exception { String documentType; String documentNumber; String userId; String correlatorId; String tokenInfo; String userIdDecoded; try { userId = exchange.getIn().getHeader("user_id").toString(); userIdDecoded = EncryptBase64.decrypt(userId); validateUserIdDecrypt(userIdDecoded); validationFields.validateUserId(exchange); documentType = userIdDecoded.split("-")[0]; documentNumber = userIdDecoded.split("-")[1]; validateTokenInfo(exchange,userId); } catch (RequiredValueException | NullPointerException re) { throw new RequiredValueException("Error validando campos de entrada para UserID"); } catch (NotFoundDataException e) { throw new NotFoundDataException(e.getMessage()); } catch (PermissionDeniedException e) { throw new PermissionDeniedException(e.getMessage()); } catch (Exception e){ // 匹配目标Base64解码异常的消息 if ("Input byte array has wrong 4-byte ending unit".equals(e.getMessage())) { // 抛出自定义异常,供全局处理器返回自定义错误 throw new Base64DecodeException("用户ID格式无效,Base64解码失败"); } // 其他异常按原有逻辑处理 throw new Exception(e.getMessage()); } // 修正原代码中Optional的用法,避免NullPointerException correlatorId= Optional.ofNullable(exchange.getIn().getHeader("x-correlator")) .map(Object::toString) .orElse(""); exchange.setProperty("isSearchByQueryParam","false"); exchange.setProperty("userId", userIdDecoded); exchange.setProperty("userIdEncrypt", userId); exchange.setProperty("correlatorId",correlatorId); exchange.setProperty("documentType", documentType); exchange.setProperty("documentNumber", documentNumber); } }
3. 关键注意事项
- 优先优化EncryptBase64类:如果有权限修改
EncryptBase64.decrypt()方法,让它抛出具体的Base64DecodeException而非通用Exception,这样就不用依赖异常消息判断,避免因消息文本变更导致逻辑失效。 - 异常消息匹配需精准:如果只能用消息判断,必须保证字符串完全匹配(包括大小写、空格和标点)。
- 全局异常处理器适配:在你的全局异常捕获组件中,新增对
Base64DecodeException的处理逻辑,返回对应的自定义错误响应即可。
内容的提问来源于stack exchange,提问作者Cesar Justo
相关产品推荐
相关产品推荐

