spring boot 使用webflux全局拦截,类似404错误

背景

要拦截类似404这种返回,添加日志返回码。所以要全局拦截404或者500返回

实现

1. 定义拦截类

package com.cmb.zhaohu.WebLogCollect.advice;import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @描述: 全局异常处理
 */
@Component
public
class RestExceptionHandler extends DefaultErrorAttributes { public Map<String, Object> getErrorAttributes(ServerRequest request, ErrorAttributeOptions options) { return assembleError(request); } private Map<String, Object> assembleError(ServerRequest request) { Map<String, Object> errorAttributes = new LinkedHashMap<>(); Throwable error = getError(request); if (error.getMessage().contains("404")) { errorAttributes.put("code", HttpStatus.NOT_FOUND); errorAttributes.put("data", error.getMessage()); } else { errorAttributes.put("code", HttpStatus.INTERNAL_SERVER_ERROR); errorAttributes.put("data", "INTERNAL SERVER ERROR"); } return errorAttributes; } }

2. 拦截返回

import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * @描述: 
 */
@Component
@Order(-2)
public class GlobalErrorWebExceptionHandler extends AbstractErrorWebExceptionHandler {
    public GlobalErrorWebExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, applicationContext);
        ServerCodecConfigurer serverCodecConfigurer = new DefaultServerCodecConfigurer();
        super.setMessageWriters(serverCodecConfigurer.getWriters());   
        //    super.setMessageReaders(serverCodecConfigurer.getReaders());  
         }    
        // 构造函数    
        @Override
        protected RouterFunction<ServerResponse> getRoutingFunction(final ErrorAttributes errorAttributes) {
            return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
        }

    private Mono<ServerResponse> renderErrorResponse(final ServerRequest request) {
        final Map<String, Object> errorPropertiesMap = getErrorAttributes(request, true);
        return ServerResponse.status(HttpStatus.OK).
                contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(errorPropertiesMap));
    }
}

结果:

如果请求404,会直接返回code和msg。

 

posted @ 2022-11-16 16:59  园圆猿  阅读(1213)  评论(0)    收藏  举报