美文网首页
springboot-alibabacloud-sentinel

springboot-alibabacloud-sentinel

作者: 前进的码农 | 来源:发表于2020-11-30 09:27 被阅读0次

直接上代码


@Component
public class CustomBlockConfig implements BlockExceptionHandler {
   public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
       R r = R.error(-101, "流控异常");
       if (e instanceof ParamFlowException) {
           r = R.error(-102, "hot-spot异常");
       }
       if (e instanceof AuthorityException) {
           r = R.error(-103, "流控异常");
       }
       if (e instanceof DegradeException) {
           r = R.error(-104, "降级异常");
       }
       if (e instanceof SystemBlockException) {
           r = R.error(-105, "系统规则异常");
       }
       if (e instanceof FlowException) {
           r = R.error(-106, "流控异常");
       }
       httpServletResponse.setStatus(200);
       httpServletResponse.setContentType("application/json;charset=utf-8");
       PrintWriter out = httpServletResponse.getWriter();
       out.print(JSON.toJSON(r).toString());
       out.flush();
       out.close();
   }
}

效果

image.png

其他

特别想试试这个异常会不会和全局异常冲突,然后代码试试

@RestControllerAdvice
@Slf4j
public class GlobalException {
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public R exceptionHandler(Exception e){
        log.error("发生业务异常!原因是:{}",e.getMessage());
        return R.error(500,e.getMessage());
    }

}
//get接口处手写一个异常
    @GetMapping("user_value")
    public String getUserValue() {
         int i = 10;
         int b =  i/0;
        log.info("name:"+name+" pwd:"+pwd);
        return "name:"+name+" pwd:"+pwd;
    }

然后f5刷起来


image.png
image.png

效果来看sentinal的流控应该在运行异常之前所以完全不受影响,可以放心coding...

相关文章

网友评论

      本文标题:springboot-alibabacloud-sentinel

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