发现这章节,有个同学问了个UrlBlockHandler不存在的问题
来源:8-22 扩展Sentinel01-错误页优化

WittChen
2022-09-22
发现这章节,有个同学问了个UrlBlockHandler不存在的问题,老师好像是没有回答这个类变成什么类了,是在考验我们处理问题的能力吗^ ^
我现在用的是sentinel1.8.5当前最新版本了吧,我想总不能会把这个功能阉割掉吧,即使没有这个类了,应该会有差不多的类代替,随便找个的放打了BlockHandler就发现idea自动提示了一个BlockExceptionHandler 这个类,进去看了下,实现了这个类,发现基本上和老师课上的UrlBlockHandler神似,然后看了下捕捉的异常类的子类,不就是课程上的几个异常吗
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
ResponseMsg msg = null;
if (e instanceof AuthorityException) {
msg = ResponseMsg.builder()
.status(101)
.msg("权限错误")
.build();
} else if (e instanceof DegradeException) {
msg = ResponseMsg.builder()
.status(102)
.msg("降级限制")
.build();
} else if (e instanceof FlowException) {
msg = ResponseMsg.builder()
.status(103)
.msg("流控")
.build();
} else if (e instanceof SystemBlockException) {
msg = ResponseMsg.builder()
.status(104)
.msg("系统规则负载")
.build();
} else if (e instanceof ParamFlowException) {
msg = ResponseMsg.builder()
.status(105)
.msg("热点参数限流")
.build();
}
httpServletResponse.setHeader("Content-Type", "application/json;charet=utf-8");
httpServletResponse.setStatus(500);
httpServletResponse.setCharacterEncoding("utf-8");
httpServletResponse.setContentType("application/json;charset=utf-8");
new ObjectMapper()
.writeValue(httpServletResponse.getWriter(), msg);
}
}
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class ResponseMsg {
private int status;
private String msg;
}
完美实现了老师课上的内容
希望后面的同学可以借鉴
写回答
1回答
-
非常赞哦!!!!!!
012022-09-29
相似问题