全局处理异常数据映射

全局处理异常数据映射

@Configuration
public class DataConverConfig {
    //处理接收的中国标准时间字符串和"null"映射Date异常
    @Bean
    public Converter<String, Date> stringDateConvert() {
        return new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                if(StringUtils.isEmpty(source) || "null".equals(source)){
                    return  null;
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = null;
                try {
                    date = sdf.parse((String) source);
                } catch (Exception e) {
                    SimpleDateFormat sdfday = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        date = sdfday.parse((String) source);
                    } catch (ParseException e1) {
                        //处理中国标准时间字符串
                        try {
                            source = source.replace("GMT", "").replaceAll("\\(.*\\)", "");
                            SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
                            date = format.parse(source);
                            return date;
                        } catch (Exception exe) {
                            return null;
                        }
                    }
                }
                return date;
            }
        };
    }
    //处理接收的"null"映射Long异常
    @Bean
    public Converter<String, Long> stringLongConvert() {
        return new Converter<String, Long>() {
            @Override
            public Long convert(String source) {
                try {
                    if ("null".equals(source)) {
                        return null;
                    }
                } catch (Exception e1) {
                    e1.printStackTrace();
                    return null;
                }
                return Long.valueOf(source);
            }
        };
    }

}
### WebFlux 全局异常处理实现方法 在WebFlux框架中,全局异常处理可以通过`@ControllerAdvice`和`@ExceptionHandler`注解来实现。这种方式不仅能够集中管理异常逻辑,还能确保整个应用程序的一致性和可维护性。 对于基于响应式的编程模型,Spring提供了`GlobalErrorAttributes`接口以及其实现类`DefaultErrorAttributes`用于收集错误信息并将其封装成Map结构传递给视图层[^1]。然而,在实际开发过程中更常用的是通过定义带有`@ControllerAdvice`的组件来进行统一异常捕捉与处理: #### 使用 `@ControllerAdvice` ```java @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public Mono<ServerResponse> handleException(ServerRequest request, Exception ex) { // 构建自定义返回体 Map<String, Object> result = new HashMap<>(); result.put("timestamp", LocalDateTime.now()); result.put("message", ex.getMessage()); // 返回HTTP状态码及JSON格式的结果集 return ServerResponse.status(HttpStatus.INTERNAL_SERVER_ERROR).body(BodyInserters.fromValue(result)); } } ``` 上述代码片段展示了如何创建一个名为`GlobalExceptionHandler`的控制器建议器,并注册了一个通用异常处理器以应对所有未被捕获的运行时异常情况。每当发生此类事件时,该函数会被触发并将详细的诊断数据反馈给客户端应用[^2]。 另外一种常见的做法是在特定条件下区分不同类型的业务逻辑错误,例如针对某个具体的服务模块设置专门化的异常映射规则: #### 针对特定服务的异常处理 ```java @RestControllerAdvice(basePackages = "com.example.cityservice.handler") public class CityHandlerExceptionResolver { private static final Logger logger = LoggerFactory.getLogger(CityHandlerExceptionResolver.class); @ExceptionHandler(GlobalException.class) public Mono<ResponseEntity<Map<String,Object>>> resolveCityServiceErrors(ServerRequest req, GlobalException e){ logger.error(e.getLocalizedMessage(),e); Map<String, Object> body = Maps.newHashMap(); body.put("code", e.getCode()); body.put("msg", e.getMessage()); return Mono.just(ResponseEntity.status(e.getStatus()).body(body)); } } ``` 这段示例说明了怎样为城市信息服务(`CityHandler`)单独配置一套完整的异常转换机制——即只有当遇到由其内部产生的`GlobalException`实例才会调用此方法进行特殊化处置;其他情况下依旧遵循默认流程继续向上冒泡直至找到匹配项为止[^3]。 最后值得注意的是,除了利用AOP切面技术外还可以借助于Reactor核心库所提供的钩子(Hooks)功能来自定义全局级别的错误恢复策略,从而进一步增强系统的健壮程度。不过这通常适用于较为复杂的场景需求分析之后再做决定[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值