sentinel自定义异常处理


package com.huqi.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration;
import org.springframework.context.annotation.Configuration;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
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.core.JsonFactory;
import com.google.gson.Gson;

import io.netty.handler.codec.json.JsonObjectDecoder;
@Configuration
public class SentinelException implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {
        MyResponse errorResponse = new MyResponse();
        // 不同的异常返回不同的提示语
        if (e instanceof FlowException) {
            errorResponse.setMsg("被限流了");
            errorResponse.setStatus(1);
        } else if (e instanceof DegradeException) {
            errorResponse.setMsg("服务降级了");
            errorResponse.setStatus(2);
        } else if (e instanceof ParamFlowException) {
            errorResponse.setMsg("被限流了");
            errorResponse.setStatus(3);
        } else if (e instanceof SystemBlockException) {
            errorResponse.setMsg("被系统保护了");
            errorResponse.setStatus(4);
        } else if (e instanceof AuthorityException) {
            errorResponse.setMsg("被授权了");
            errorResponse.setStatus(5);
        }

        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
      response.getWriter().print(new Gson().toJson(errorResponse));
    }
}

/**
 * 简单的响应结构体
 */
class MyResponse {
    private Integer status;
    private String msg;
    public Integer getStatus() {
        return status;
    }
    public static Object builder() {
        // TODO Auto-generated method stub
        return null;
    }
    public void setStatus(Integer status) {
        this.status = status;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM