介绍
:::tips 默认情况下,发生限流、降级、授权拦截时,都会抛出异常到调用方,异常结果都是flow limmiting(限流),这样不够友好,无法得知是限流、降级还是授权拦截
如果要自定义异常返回结果,需要实现BlockExceptionHandler接口,并重写handle方法,这个方法有三个参数:
- HttpServletRequest request:request对象
- HttpServletResponse response:response对象
- BlockExceptione:被Sentinel拦截时抛出的异常
这里的BlockException包含多个不同的子类:
- FlowException:限流异常
- ParamFlowException:热点参数限流的异常
- DegradeException:降级异常
- AuthorityException:授权规则异常
SystemBlockException:系统规则异常 :::
自定义异常处理
:::tips 在服务提供者中定义BlockExceptionHandler的实现类,并实现handle方法来自定义异常,当发生限流、降级、授权拦截的异常时,会返回不同的异常消息 :::
//注册到Spring容器中
@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 + "}");
}
}