Sentinel授权规则-自定义异常结果

默认情况下,发生限流、降级、授权拦截时,都会抛出异常到调用方。如果要自定义异常时的返回结果,需要实现BlockExceptionHandler接口:

public class SentinelExceptionHandler implements BlockExceptionHandler {
    /**    
     * 处理请求被限流、降级、授权拦截时抛出的异常:BlockException
     */
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception;
}

 

而BlockException包含很多个子类,分别对应不同的场景:

异常                       说明
FlowException             限流异常
ParamFlowException        热点参数限流的异常
DegradeException          降级异常
AuthorityException        授权规则异常
SystemBlockException      系统规则异常

 

自定义异常结果
我们在order-service中定义类,实现BlockExceptionHandler接口:

@Component
public class SentinelExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String msg = "未知异常";
        int status = 429;

        if (e instanceof FlowException) {
            msg = "请求被限流了";
        } else if (e instanceof ParamFlowException) {
            msg = "请求被热点参数限流";
        } else if (e instanceof DegradeException) {
            msg = "请求被降级了";
        } else if (e instanceof AuthorityException) {
            msg = "没有权限访问";
            status = 401;
        }

        response.setContentType("application/json;charset=utf-8");
        response.setStatus(status);
        response.getWriter().println("{\"msg\": " + msg + ", \"status\": " + status + "}");
    }
}

 

总结
获取请求来源的接口是什么?
RequestOriginParser

处理BlockException的接口是什么?
BlockExceptionHandler

上一篇:SpringCloudAlibaba--服务限流--热点key限流


下一篇:Sentinel隔离和降级-熔断降级原理