Netflix Feign - Propagate Status and Exception through Microservices

后端 未结 6 810
予麋鹿
予麋鹿 2021-02-05 05:04

I\'m using Netflix Feign to call to one operation of a Microservice A to other other operation of a Microservice B which validates a code using Spring Boot.

The operation

6条回答
  •  故里飘歌
    2021-02-05 05:31

    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 the way you need it (see here):

    @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 from Microservice B. You can go further and also return the original response body:

    response.getOutputStream().write(e.content());
    

提交回复
热议问题