规范优化

pull/137/head
koltZhang 2024-08-31 15:15:50 +08:00
parent 8a43cd4bef
commit 0724f10196
2 changed files with 13 additions and 8 deletions

View File

@ -6,12 +6,15 @@ import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
/**
* SpringMyServicebeanbean
*/
@AutoConfiguration
@Slf4j
public class SentinelExceptionHandlerAutoConfiguration {
@Bean
@ConditionalOnMissingBean // 当Spring容器中不存在MyService类型的bean时才创建这个bean
@ConditionalOnMissingBean
public SentinelExceptionHandler sentinelExceptionHandler() {
return new SentinelExceptionHandler();
}

View File

@ -1,6 +1,7 @@
package cn.iocoder.yudao.framework.sentinel.core.handler;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.servlet.ServletUtils;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
@ -8,16 +9,19 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Sentinel
*/
public class SentinelExceptionHandler implements BlockExceptionHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) {
String msg = "未知异常";
int status = HttpStatus.TOO_MANY_REQUESTS.value();
if (e instanceof FlowException) {
@ -33,8 +37,6 @@ public class SentinelExceptionHandler implements BlockExceptionHandler {
msg = "系统规则限流或降级";
}
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.setStatus(status);
response.getOutputStream().println(JSON.toJSONString(CommonResult.error(status,msg)));
ServletUtils.writeJSON(response, CommonResult.error(status, msg));
}
}