SpringCloud-gateway下WebFlux响应式编程自定义异常信息

在springCloud-gateway下实现自定义异常信息捕获并抛出,实现代码如下:


/**
 * @program: 
 * @description: 全局异常处理
 * @author: Mr.Peach
 * @create: 2022-07-04 15:08
 **/
@Component
public class GlobalExceptionConfiguration implements ErrorWebExceptionHandler {

    @Override
    public Mono handle(ServerWebExchange exchange, Throwable ex) {
        //存放响应到response的数据
        Map result = new HashMap<>(3);
        //1.获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //2.response是否结束  用于多个异常处理时候
        if (response.isCommitted()) {
            return Mono.error(ex);
        }
        //2.设置响应头类型
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        //3.设置响应状态吗
        if (ex instanceof GateWayException) {
            response.setStatusCode(HttpStatus.OK);
        } else {
            response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        //4.设置响应内容
        return response
                .writeWith(Mono.fromSupplier(() -> {
                    DataBufferFactory bufferFactory = response.bufferFactory();
                    GateWayException gateWayException = (GateWayException)ex;
                    result.put("code",gateWayException.getCode());
                    result.put("data",null);
                    result.put("message", gateWayException.getMessage());
                    ObjectMapper objectMapper = new ObjectMapper();
                    try {
                        //设置响应到response的数据
                        return bufferFactory.wrap(objectMapper.writeValueAsBytes(result));
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                        return null;
                    }
                }));
    }
}

实现token校验等拦截,只需在使用的地方抛出自定义异常类即可

你可能感兴趣的:(spring积累,spring,cloud,gateway,java)