Feign ErrorDecoder:检索原始消息



我使用ErrorDecoder返回正确的异常,而不是500状态代码。

有没有一种方法可以在解码器中检索原始消息。我可以看到它在FeignException中,但不在解码方法中。我只有"状态代码"和一个空的"原因"。

public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
@Override
public Exception decode(String s, Response response) {
switch (response.status()) {
case 404:
return new FileNotFoundException("File no found");
case 403:
return new ForbiddenAccessException("Forbidden access");
}
return errorDecoder.decode(s, response);
}
}

这里的原始消息:"消息":"访问文件被禁止">

feign.FeignException: status 403 reading ProxyMicroserviceFiles#getUserRoot(); content:
{"timestamp":"2018-11-28T17:34:05.235+0000","status":403,"error":"Forbidden","message":"Access to the file forbidden","path":"/root"}

此外,我使用FeignClient接口就像使用RestController一样,所以我不使用任何其他填充了代理的Controler来封装方法调用。

@RestController
@FeignClient(name = "zuul-server")
@RibbonClient(name = "microservice-files")
public interface ProxyMicroserviceFiles {
@GetMapping(value = "microservice-files/root")
Object getUserRoot();
@GetMapping(value = "microservice-files/file/{id}")
Object getFileById(@PathVariable("id") int id);
}

如果您想获得响应有效负载主体,除了Feign异常,只需使用以下方法:

feignException.contentUTF8();

示例:

try {
itemResponse = call(); //method with the feign call
} catch (FeignException e) {
logger.error("ResponseBody: " + e.contentUTF8());
}

这里有一个解决方案,消息实际上是作为流在响应体中的。

package com.clientui.exceptions;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.*;
import java.io.*;
public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
@Override
public Exception decode(String s, Response response) {
String message = null;
Reader reader = null;
try {
reader = response.body().asReader();
//Easy way to read the stream and get a String object
String result = CharStreams.toString(reader);
//use a Jackson ObjectMapper to convert the Json String into a 
//Pojo
ObjectMapper mapper = new ObjectMapper();
//just in case you missed an attribute in the Pojo     
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//init the Pojo
ExceptionMessage exceptionMessage = mapper.readValue(result, 
ExceptionMessage.class);
message = exceptionMessage.message;
} catch (IOException e) {
e.printStackTrace();
}finally {
//It is the responsibility of the caller to close the stream.
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
switch (response.status()) {
case 404:
return new FileNotFoundException(message == null ? "File no found" : 
message);
case 403:
return new ForbiddenAccessException(message == null ? "Forbidden 
access" : message);
}
return errorDecoder.decode(s, response);
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public static class ExceptionMessage{
private String timestamp;
private int status;
private String error;
private String message;
private String path;
}
}

建议使用输入流而不是读取器,并将其映射到对象。

package com.clientui.exceptions;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.io.CharStreams;
import feign.Response;
import feign.codec.ErrorDecoder;
import lombok.*;
import java.io.*;
public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
@Override
public Exception decode(String s, Response response) {
String message = null;
InputStream responseBodyIs = null;
try {
responseBodyIs = response.body().asInputStream();
ObjectMapper mapper = new ObjectMapper();
ExceptionMessage exceptionMessage = mapper.readValue(responseBodyIs, ExceptionMessage.class);
message = exceptionMessage.message;
} catch (IOException e) {
e.printStackTrace();
// you could also return an exception
return new errorMessageFormatException(e.getMessage());
}finally {
//It is the responsibility of the caller to close the stream.
try {
if (responseBodyIs != null)
responseBodyIs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
switch (response.status()) {
case 404:
return new FileNotFoundException(message == null ? "File no found" :
message);
case 403:
return new ForbiddenAccessException(message == null ? "Forbidden access" : message);
}
return errorDecoder.decode(s, response);
}
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public static class ExceptionMessage{
private String timestamp;
private int status;
private String error;
private String message;
private String path;
}
}

关于公认答案的一些重构和代码风格:

@Override
@SneakyThrows
public Exception decode(String methodKey, Response response) {
String message;
try (Reader reader = response.body().asReader()) {
String result = StringUtils.toString(reader);
message = mapper.readValue(result, ErrorResponse.class).getMessage();
}
if (response.status() == 401) {
return new UnauthorizedException(message == null ? response.reason() : message);
}
if (response.status() == 403) {
return new ForbiddenException(message == null ? response.reason() : message);
}
return defaultErrorDecoder.decode(methodKey, response);
}

如果你和我一样,真的只是想在没有所有这些自定义解码器和样板的情况下从失败的Feign调用中获得内容,那么有一种方法可以做到这一点。

如果我们在创建FeignException并且存在响应体时查看它,它会像这样组装异常消息:

if (response.body() != null) {
String body = Util.toString(response.body().asReader());
message += "; content:n" + body;
}

因此,如果您在寻找响应主体,您可以通过解析Exception消息来提取它,因为它是由换行符分隔的。

String[] feignExceptionMessageParts = e.getMessage().split("n");
String responseContent = feignExceptionMessageParts[1];

如果你想要这个物体,你可以使用类似Jackson的东西:

MyResponseBodyPojo errorBody = objectMapper.readValue(responseContent, MyResponseBodyPojo.class);

我并不认为这是明智的做法或最佳做法。

原始消息位于响应正文中,已得到响应。然而,我们可以使用Java 8 Streams来减少样板文件的数量:

public class CustomErrorDecoder implements ErrorDecoder {
private final ErrorDecoder errorDecoder = new Default();
@Override
public Exception decode(String s, Response response) {
String body = "4xx client error";
try {
body = new BufferedReader(response.body().asReader(StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("n"));
} catch (IOException ignore) {}
switch (response.status()) {
case 404:
return new FileNotFoundException(body);
case 403:
return new ForbiddenAccessException(body);
}
return errorDecoder.decode(s, response);
}
}

关于Kotlin:

@Component
class FeignExceptionHandler : ErrorDecoder {

override fun decode(methodKey: String, response: Response): Exception {
return ResponseStatusException(
HttpStatus.valueOf(response.status()),
readMessage(response).message
)
}
private fun readMessage(response: Response): ExceptionMessage {
return response.body().asInputStream().use {
val mapper = ObjectMapper()
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
mapper.readValue(it, ExceptionMessage::class.java)
}
}
}
data class ExceptionMessage(
val timestamp: String? = null,
val status: Int = 0,
val error: String? = null,
val message: String? = null,
val path: String? = null
)

最新更新