zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    20170419数据结构
    20170418 random函数和range函数
    20170418 sum函数、
    20170417嵌套循环
    20170417循环(loop)
    linux 输入输出重定向
    cut 命令-截取文件中指定内容
    read 命令-从键盘读取变量的值
    xargs-命令
    find 在目录中查找文件
  • 原文地址:https://www.cnblogs.com/linjiqin/p/15375328.html
Copyright © 2011-2022 走看看