我有一个名为“hr”的spring云服务,以及一个使用Feign作为客户端调用hr服务的api网关服务。如果 hr 服务发生任何异常,它会返回一个类型为 .json 的 json 消息ResponseEntity<ServiceException>
。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
注释类来尝试处理异常。但不幸的是,它不起作用。我可能是因为控制器没有通过某些过滤器抛出异常,所以@ControllerAdvice
注释不起作用。
有人可以给我一些关于案例的建议吗?