如何在Golang Hystrix断路器中处理4xx错误

huangapple go评论83阅读模式
英文:

How to handle 4xx errors in Golang Hystrix circuit breaker

问题

在编写断路器时,我正在对上游服务进行 API 调用,该调用可能会返回 5xx 或 4xx 错误。我希望只考虑 5xx 错误来打开断路器,而 4xx 错误应该按正常方式处理。

	resp, err := clients.DoHTTPCall(url, "POST", payload, ConnectionTimeOut, []string{config.Config.ContactConfig.AuthTokenHeaderNameInLoadRequest}, []string{authToken})
	logging.Info("test", "%v", *resp)
	if err != nil {
		common.TrackStats(common.CurrencyToCountryMap[currencyCode], userType, LOAD_CONTACT_DATA_API, common.API_ERROR)
		//logging.Error(logtag, "Error on loadContactLoadData request=%v err=%v contactLoadApiMsgId=%v", request, err, contactLoadApiMsgId)
		return responses.NewError(responses.InternalServerError, err.Error())
	}
	return nil
}, circuitbreaker.WithFallback(contactLoadFallback()))```



<details>
<summary>英文:</summary>

While writing a circuit breaker, I am making an api call to upstream service, which will either give 5xx or 4xx errors. I want to consider only 5xx errors for opening the circuit while 4xx should be handled normally. 

```	circuitbreaker.Do(ctx, circuitName, func() error {
		resp, err := clients.DoHTTPCall(url, &quot;POST&quot;, payload, ConnectionTimeOut, []string{config.Config.ContactConfig.AuthTokenHeaderNameInLoadRequest}, []string{authToken})
		logging.Info(&quot;test&quot;, &quot;%v&quot;, *resp)
		if err != nil {
			common.TrackStats(common.CurrencyToCountryMap[currencyCode], userType, LOAD_CONTACT_DATA_API, common.API_ERROR)
			//logging.Error(logtag, &quot;Error on loadContactLoadData request=%v err=%v contactLoadApiMsgId=%v&quot;, request, err, contactLoadApiMsgId)
			return responses.NewError(responses.InternalServerError, err.Error())
		}
		return nil
	}, circuitbreaker.WithFallback(contactLoadFallback()))```

</details>


# 答案1
**得分**: 1

只有在出现5xx错误时才返回错误。Hystrix会累积从函数返回的错误,以检查是否应该打开电路。您仍然可以使用resp中的StatusCode来单独处理每个状态码。

<details>
<summary>英文:</summary>

Just return error only when it is 5xx. Hystrix will accumulate the error returned from function to check if the circuit should be opened. You can still use StatusCode in resp to handle each status code separately.

</details>



# 答案2
**得分**: 0

```go
hystrix.Go(config.Config.CircuitSetting.ContactCircuitName, func() error {
    resp, err := clients.DoHTTPCall(url, "GET", payload, ConnectionTimeOut, []string{config.Config.ContactConfig.AuthTokenHeaderNameInLoadRequest}, authToken)
    if resp != nil {
        response = *resp
    }
    if err != nil {
        logging.Error(logtag, "请求错误=%v 错误=%v", request, err)
        return err
    } else if resp.StatusCode >= 500 {
        return err //发送断路器错误
    }
    return nil
}, func(err error) error {
    //回退函数
    circuit, _, _ := hystrix.GetCircuit(config.Config.CircuitSetting.ContactCircuitName)
    logging.Info(logtag, "断路器是否打开:%v", circuit.IsOpen())
    return err
})
英文:
hystrix.Go(config.Config.CircuitSetting.ContactCircuitName, func() error {
		resp, err := clients.DoHTTPCall(url, &quot;GET&quot;, payload, ConnectionTimeOut, []string{config.Config.ContactConfig.AuthTokenHeaderNameInLoadRequest}, authToken)
		if resp != nil {
			response = *resp
		}
		if err != nil {
			logging.Error(logtag, &quot;Error on request=%v err=%v&quot;, request, err)
			return err
		} else if resp.StatusCode &gt;= 500 {
			return err //send circuitnbreaker error
		}
		return nil
	}, func(err error) error {
        //fallabck function
		circuit, _, _ := 
        hystrix.GetCircuit(config.Config.CircuitSetting.ContactCircuitName)
		logging.Info(logtag, &quot;Is circuit Open: %v&quot;, circuit.IsOpen())
		return err
	})

</details>



huangapple
  • 本文由 发表于 2023年3月9日 18:12:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/75683150.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定