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.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.system.SystemBlockException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
 
@Configuration
public class SentinelConfiguration {
 
    @Bean
    public BlockExceptionHandler blockExceptionHandler() {
        return new BlockExceptionHandler() {
            @Override
            public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
                // 可以根据不同的异常类型进行不同的处理
                if (e instanceof FlowException) {
                    // 处理限流异常
                } else if (e instanceof DegradeException) {
                    // 处理降级异常
                } else if (e instanceof SystemBlockException) {
                    // 处理系统保护异常
                } else {
                    // 其他异常处理
                }
                // 设置响应状态码和内容
                response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("您的请求过多,请稍后再试");
            }
        };
    }
}这个代码实例中,我们定义了一个BlockExceptionHandler,用于处理Sentinel的限流、降级和系统保护异常。在handle方法中,我们根据异常类型进行了不同异常的处理,并设置了响应状态码和内容,返回友好的提示信息。这样,当Sentinel触发限