feign 客户端访问 api,拿到错误码(400、404、500...)时,默认会覆盖原本的错误信息,要获取原本的错误消息,可以写一个 ErrorDecoder 覆盖掉原本的默认实现:
import feign.Response;
import feign.codec.ErrorDecoder;
import io.undertow.util.BadRequestException;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
/**
* <p> 2023/3/1 </p>
* 拦截错误信息,将原本的错误信息返回
*
* @author Fqq
*/
@Component
public class RetreiveMessageErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
@Override
public Exception decode(String methodKey, Response response) {
String message;
try (InputStream bodyIs = response.body().asInputStream()) {
// 错误信息的 inputStream 转字符串
message = new String(bodyIs.readAllBytes(), StandardCharsets.UTF_8);
} catch (IOException e) {
return new Exception(e.getMessage(), e);
}
switch (response.status()) {
case 400:
return new BadRequestException(message);
case 404:
return new NotFoundException("Not found");
default:
return errorDecoder.decode(methodKey, response);
}
}
}