springboot-alibabacloud-sentinel-自定义返回-03

直接上代码


@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...

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容