Sentinel异常处理

全局异常处理

继承Sentinel的BlockExceptionHandler拦截器重写拦截方法,针对 BlockException 进行异常处理即可。
在这里插入图片描述

@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
        Logger logger = LoggerFactory.getLogger(MyBlockExceptionHandler.class);
        //Sentinel规则的详细信息
        logger.info("BlockExceptionHandler BlockException ============ " + e.getRule());

        Result r = null;
        if (e instanceof FlowException) {
            r = Result.error(100, "接口限流了");
        } else if (e instanceof DegradeException) {
            r = Result.error(101, "服务降级了");
        } else if (e instanceof ParamFlowException) {
            r = Result.error(102, "热点参数限流了");
        } else if (e instanceof SystemBlockException) {
            r = Result.error(103, "触发系统保护规则了");
        } else if (e instanceof AuthorityException) {
            r = Result.error(104, "授权规则不通过");
        }

        //返回json数据
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        new ObjectMapper().writeValue(response.getWriter(), r);
    }
}

局部异常处理

针对一个接口,做自定义的异常处理。在接口上使用注解@SentinelResource,可以指定异常处理方法,但异常方法必须与该接口在同一目录位置,且保持相同类型和请求参数,否则无效。

	 /**
     * @SentinelResource
     * value:资源名称
     * blockHandler:异常拦截
     */
	@RequestMapping("/flow")
    @SentinelResource(value = "flow", blockHandler = "flowBlockHandler")
    public String flow() {
        return "正常访问";
    }

    /**
     * 异常拦截方法
     * 必须同接口在同一目录位置,且与流控方法保持同类型,同参数
     */
    public String flowBlockHandler(BlockException blockException) {
        return "接口被流控了";
    }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

-小龙人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值