Tag Archives: # SpringCloud

Sentinel could not find the urlblockhandler interface solution

Recently, when I was learning spring cloud Alibaba, I needed sentinel for traffic management and control. When I configured the unified handling of returned exceptions, the implementation of urlblockhandler became popular. The reason is that I used sentinel 2.2.1.release, which was officially changed to blockexceptionhandler.

 

Solution: Inheritance   BlockExceptionHandler   The specific code is as follows:

package com.sentinel;

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

import org.springframework.stereotype.Component;

import com.Enum.RequestMsgEnum;
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 com.global.BaseController;
 
/**
 * Custom sentinel exception return message
 */
@Component
public class MyUrlBlockHandler extends BaseController implements BlockExceptionHandler{

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws Exception {
        String msg = null;
        if (ex instanceof FlowException) {
            msg = "Flow is restricted";
        } else if (ex instanceof DegradeException) {
            msg = "Degraded";
        } else if (ex instanceof ParamFlowException) {
            msg = "Hotspot parameter flow restriction";
        } else if (ex instanceof SystemBlockException) {
            msg = "System rule (load/... Not satisfied)";
        } else if (ex instanceof AuthorityException) {
            msg = "Authorization rule not passed";
        }
        // http status code
        response.setStatus(500);
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setContentType("application/json;charset=utf-8");
        // spring mvc comes with a json manipulation tool called jackson
        new ObjectMapper()
            .writeValue(
                response.getWriter(),
                this.responseResult(RequestMsgEnum.Failtrue, msg)
            );
    }
}

Note: the basecontroller class is my own definition class. The custom format is returned to the front end and needs to be modified according to my own needs.