spring feign client exception handling

后端 未结 3 1698
慢半拍i
慢半拍i 2021-02-09 03:01

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

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

    @RequestMapping(
                    


        
相关标签:
3条回答
  • 2021-02-09 03:34

    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

    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()) : "";
    

    Exemple :

    @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)
            }
        };
    }
    

    }

    0 讨论(0)
  • 2021-02-09 03:50

    There's a ErrorDecored interface for that like it says in the documentation

    The answer above about FallbackFactory is viable but falls into some other layer of abstraction.

    0 讨论(0)
  • 2021-02-09 03:59

    Not the same issue, but this helped in my situation. OpenFeign's FeignException doesn't bind to a specific HTTP status (i.e. doesn't use Spring's @ResponseStatus annotation), which makes Spring default to 500 whenever faced with a FeignException. That's okay because a FeignException can have numerous causes that can't be related to a particular HTTP status.

    However you can change the way that Spring handles FeignExceptions. Simply define an ExceptionHandler that handles the FeignException

    @RestControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(FeignException.class)
        public String handleFeignStatusException(FeignException e, HttpServletResponse response) {
            response.setStatus(e.status());
            return "feignError";
        }
    
    }
    

    This example makes Spring return the same HTTP status that you received

    0 讨论(0)
提交回复
热议问题