OpenFeign配置(全局异常解析、请求超时)

自定义全局异常

package com.snoob.baseFeign.wConfig;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.snoob.springcloudalibaba.base.BaseFeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import feign.form.util.CharsetUtil;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.io.Reader;
import java.text.MessageFormat;

/**
 * @描述: 自定义Feign错误信息
 * @作者: lixing
 * @日期 2021/4/14 13:01
 */
@Configuration
public class FeignErrorDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        Reader reader = null;
        try {
            reader = response.body().asReader(CharsetUtil.UTF_8);
            String errMsg = Util.toString(reader);
            if (errMsg.contains("Load balancer does not contain an instance for the service")) {
                // Load balancer does not contain an instance for the service serviceAdmin
                String pathTemp = errMsg.replace("Load balancer does not contain an instance for the service", "").trim();
                return new BaseFeignException(MessageFormat.format("{0}: {1}", pathTemp, errMsg));
            } else {
                JSONObject errMsgJsonObj = JSON.parseObject(errMsg);
                //            {
                //                "path": "/serviceUser/auth/login",
                //                "trace": "java.lang.ArithmeticException: / by zero\r\n\tat",
                //                "error": "Internal Server Error",
                //                "message": "/ by zero",
                //                "timestamp": "2021-06-26 21:42:49",
                //                "status": 500
                //            }
                String pathTemp = errMsgJsonObj.getString("path");
                String messageTemp = errMsgJsonObj.getString("message");
                return new BaseFeignException(MessageFormat.format("{0}: {1}", pathTemp, messageTemp));
            }
        } catch (IOException e) {
            return new BaseFeignException(MessageFormat.format("自定义Feign错误信息出错:{0}", e.getMessage()));
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // return decode(methodKey, response);
    }
}

请求超时

# feign配置
feign:
  httpclient:
    enabled: true # 默认开启
  client:
    config:
      default: # 默认全局服务调用超时配置
        connectTimeout: 2000 # 连接超时
        readTimeout: 2000 # 接口请求超时
      serviceAdmin: # 自定义服务调用超时配置
        connectTimeout: 100000
        readTimeout: 100000

OkHttpClient请求超时

public static void main(String[] args) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(1, TimeUnit.SECONDS)
                .readTimeout(2, TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder()
                .url("http://127.0.0.1:8888/3PL/testHttp")
                .header("token", "token_9c33f844-ffb7-4765-88ae-258624a5f526")
                .get()
                .build();
        String message = null;
        String result = null;
        try {
            Response response = client.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new RuntimeException("请求失败");
            }
            message = response.message();
            result = response.body().string();
        } catch (SocketTimeoutException socketTimeoutException) {
            if ("connect timed out".equalsIgnoreCase(socketTimeoutException.getMessage())) {
                log.info("连接超时");
            }
        } catch (InterruptedIOException interruptedException) {
            if ("Read timed out".equalsIgnoreCase(interruptedException.getCause().getMessage())) {
                log.info("响应超时");
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
在Vue中,可以通过全局设置来定义请求超时的行为。首先,你可以使用axios来发送请求,并在请求配置中设置超时时间。具体步骤如下: 1. 在项目中安装axios:可以使用npm或yarn来安装axios,例如:`npm install axios` 2. 在Vue项目的入口文件(通常是main.js)中引入axios: ```javascript import axios from 'axios'; ``` 3. 创建一个axios实例,并进行全局配置: ```javascript const instance = axios.create({ timeout: 5000, // 设置请求超时时间(单位:毫秒) }); ``` 4. 将axios实例挂载到Vue的原型上,以便在整个应用中可以使用: ```javascript Vue.prototype.$http = instance; ``` 5. 现在,你可以在任何Vue组件中使用`this.$http`来发送请求,并设置请求超时时间: ```javascript this.$http.get('/api/data', { timeout: 3000 }) .then(response => { // 处理响应数据 }) .catch(error => { // 处理错误 }); ``` 通过以上步骤,你可以在Vue中全局设置请求超时时间。在发送请求时,如果超过设置的超时时间,请求将会被中止,并执行相应的错误处理代码。这样可以确保请求不会无限期地等待。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [vue-resource请求超时timeout设置](https://blog.csdn.net/weixin_39603492/article/details/111753269)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大能嘚吧嘚

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值