全局异常处理
继承Sentinel的BlockExceptionHandler拦截器重写拦截方法,针对 BlockException 进行异常处理即可。
@Component
public class MyBlockExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest httpServletRequest, HttpServletResponse response, BlockException e) throws Exception {
Logger logger = LoggerFactory.getLogger(MyBlockExceptionHandler.class);
//Sentinel规则的详细信息
logger.info("BlockExceptionHandler BlockException ============ " + e.getRule());
Result r = null;
if (e instanceof FlowException) {
r = Result.error(100, "接口限流了");
} else if (e instanceof DegradeException) {
r = Result.error(101, "服务降级了");
} else if (e instanceof ParamFlowException) {
r = Result.error(102, "热点参数限流了");
} else if (e instanceof SystemBlockException) {
r = Result.error(103, "触发系统保护规则了");
} else if (e instanceof AuthorityException) {
r = Result.error(104, "授权规则不通过");
}
//返回json数据
response.setStatus(500);
response.setCharacterEncoding("utf-8");
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
new ObjectMapper().writeValue(response.getWriter(), r);
}
}
局部异常处理
针对一个接口,做自定义的异常处理。在接口上使用注解@SentinelResource,可以指定异常处理方法,但异常方法必须与该接口在同一目录位置,且保持相同类型和请求参数,否则无效。
/**
* @SentinelResource
* value:资源名称
* blockHandler:异常拦截
*/
@RequestMapping("/flow")
@SentinelResource(value = "flow", blockHandler = "flowBlockHandler")
public String flow() {
return "正常访问";
}
/**
* 异常拦截方法
* 必须同接口在同一目录位置,且与流控方法保持同类型,同参数
*/
public String flowBlockHandler(BlockException blockException) {
return "接口被流控了";
}