package com.ssyf.gateway.error;//package com.ssyf.gateway.error;

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;
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.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author huwei
 * @date 2024/9/11 15:07
 */
@Order(-1)
@Configuration
@Component
public class GlobalBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        System.out.println("限流： " + e.getRule());
        Map<Object,Object> map = new HashMap<>();
        if(e instanceof FlowException){
            //接口限流
            map.put(100 ,"接口限流");
        }else if(e instanceof DegradeException){
            //熔断
            map.put(101 ,"服务限流");
        }else if(e instanceof ParamFlowException){
            //热点
            map.put(102 ,"热点限流");
        }else if(e instanceof SystemBlockException){
            //系统规则
            map.put(103 ,"系统限流");
        }else if(e instanceof AuthorityException){
            //授权规则
            map.put(104 ,"系统规则");
        }else{
            //默认
        }
        //格式
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //输出
        new ObjectMapper().writeValue(response.getWriter() ,map);
    }
}
