如何使自定义的ErrorDecoder和@ExceptionHandler在Spring云中一起工作

时间:2016-07-10 14:00:26

标签: spring-cloud netflix-feign spring-cloud-feign

我有一个名为“hr”的Spring云服务,以及一个使用Feign作为客户端来调用hr服务的api网关服务。如果hr服务中发生任何异常,它将返回类型为ResponseEntity<ServiceException>的json消息。 ServiceException就像:

public class ServiceException extends Exception {

    private String errorCode;
    // constructors omitted
}

在api网关服务中,我自定义了feign.codec.ErrorDecoder

@Service
public class SpringWebClientErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(response.body().asInputStream(), ServiceException.class);
        } catch (IOException e) {
            logger.info("Failed to process response body");
            throw new RuntimeException("Failed to process response body.", e);
        }
    }

}

它可以正常获取ServiceException,我可以得到类似的错误消息:

{
  "timestamp": 1468158273181,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "ServiceException",
  "message": "sn should not be empty",
  "path": "/employee"
}

我想更改错误消息的格式并至少添加errorCode类的ServiceException字段,因此我添加了一个@ControllerAdvice注释类来尝试处理异常。但不幸的是,它不起作用。我可能是因为Controller不会通过某些过滤器抛出异常,因此@ControllerAdvice注释不起作用。

请问有人给我一些案例建议吗。

0 个答案:

没有答案