您的位置:首页 > 编程语言 > Java开发

Spring Boot FeignClient 捕获异常信息

2018-01-18 00:00 661 查看
摘要: 将FeignClient解析后的Exception 转换成标准的Spring Rest Exception

FeignClient 默认的解析器:

public static FeignException errorStatus(String methodKey, Response response) {
// 这里做了处理
String message = format("status %s reading %s", response.status(), methodKey);
try {
if (response.body() != null) {
String body = Util.toString(response.body().asReader());
message += "; content:\n" + body;
}
} catch (IOException ignored) { // NOPMD
}
return new FeignException(response.status(), message);
}

截获的异常如下:

status 400 reading PaymentInterface#methodName(ParamType,ParamType);

content: {"type":"http://httpstatus.es/404","title":"未找到资源","status":400,"detail":"这里是详细的异常信息"} ->

cz.jirutka.spring.exhandler.messages.ErrorMessage

自定义解析器:

@Configuration
public class FeignErrorDecoder implements ErrorDecoder {

@Override
public Exception decode(String methodKey, Response response) {
try {
// 这里直接拿到我们想过的异常信息
String message = Util.toString(response.body().asReader());
return new RuntimeException(message);
} catch (IOException ignored) {
}
return decode(methodKey, response);
}
}

异常信息如下:

{type: "http://httpstatus.es/404",title: "未找到资源",status: 400,detail: "这里是详细的异常信息"}

此时就能得到我们的Rest风格的Exception了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Feign Spring Boot