美文网首页
Sentinel 异常统一处理

Sentinel 异常统一处理

作者: 赵哥窟 | 来源:发表于2022-05-09 17:53 被阅读0次

    @ResourceSentinel 注解太麻烦,每个接口都加注解
    Sentinel 限流返回的提示太不友好了,改成自定义的。

    package com.tansun.springcloud.gateway.web.config;
    
    import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler;
    import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
    import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
    import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
    import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
    import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
    import com.alibaba.fastjson.JSONObject;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.web.reactive.function.BodyInserters;
    import org.springframework.web.reactive.function.server.ServerResponse;
    import org.springframework.web.server.ServerWebExchange;
    import reactor.core.publisher.Mono;
    
    @Configuration
    public class SentinelExceptionConfig implements BlockRequestHandler {
    
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                JSONObject resultObj = new JSONObject();
                if(throwable instanceof FlowException){
                    resultObj.put("code",100);
                    resultObj.put("msg","接口限流");
                }if(throwable instanceof DegradeException){
                    resultObj.put("code",101);
                    resultObj.put("msg","服务降级");
                }if(throwable instanceof ParamFlowException){
                    resultObj.put("code",102);
                    resultObj.put("msg","热点参数限流");
                }if(throwable instanceof SystemBlockException){
                    resultObj.put("code",103);
                    resultObj.put("msg","触发系统保护规则");
                }if(throwable instanceof AuthorityException){
                    resultObj.put("code",104);
                    resultObj.put("msg","授权规则不通过");
                }
                return ServerResponse.status(HttpStatus.BAD_GATEWAY)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromValue(resultObj));
        };
    }
    
    
    

    相关文章

      网友评论

          本文标题:Sentinel 异常统一处理

          本文链接:https://www.haomeiwen.com/subject/udnhurtx.html