春季假客户端异常处理 [英] spring feign client exception handling

查看:125
本文介绍了春季假客户端异常处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些客户客户端要发送其他微服务请求.

I have some fiegn client to send request other micro service.

@FeignClient(name="userservice")
public interface UserClient {

    @RequestMapping(
            method= RequestMethod.GET,
                      path = "/userlist")
    String getUserByid(@RequestParam(value ="id") String id);

}

现在我正在发送这样的请求

Now I am sending request like this

try {
    String responseData = userClient.getUserByid(id);
    return responseData;
    }

catch(FeignException e)
 {
 logger.error("Failed to get user", id);
}

catch (Exception e) 
{
 logger.error("Failed to get user", id);
}

这里的问题是,如果发生任何FeignException,我没有得到任何错误代码.

Here the problem is if any FeignException happens I dont get any error code.

我需要在其他APIS中发送相应的错误代码以发送给调用者

I need to send a corresponding error codes in other APIS to send to caller

那么如何提取错误代码?我想提取错误代码并建立一个responseEntity

So how to extract the error code? I want to extract error code and build a responseEntity

我得到了代码,但是不知道我可以在我的函数中使用多少.

I got this code but dont know how exactly I can use in my function.

推荐答案

您是否尝试在伪装客户端上实现FallbackFactory?

did you try to implement FallbackFactory on your feign client ?

https://cloud.spring.io/spring-cloud-netflix/multi/multi_spring-cloud-feign.html#spring-cloud-feign-hystrix-fallback

在create方法上,返回之前,您可以使用以下代码段获取http状态代码:

On the create method, before return, you can retrieve the http status code with this snippet :

String httpStatus = cause instanceof FeignException ? Integer.toString(((FeignException) cause).status()) : "";

示例:

@FeignClient(name="userservice", fallbackFactory = UserClientFallbackFactory.class)
public interface UserClient {

    @RequestMapping(
            method= RequestMethod.GET,
                      path = "/userlist")
    String getUserByid(@RequestParam(value ="id") String id);

}


@Component
static class UserClientFallbackFactory implements FallbackFactory<UserClient> {
    @Override
    public UserClient create(Throwable cause) {

     String httpStatus = cause instanceof FeignException ? Integer.toString(((FeignException) cause).status()) : "";

     return new UserClient() {
        @Override
        public String getUserByid() {
            logger.error(httpStatus);
            // what you want to answer back (logger, exception catch by a ControllerAdvice, etc)
        }
    };
}

}

这篇关于春季假客户端异常处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆