Spring Boot FeignClient 捕獲異常信息

FeignClient 默認的解析器:java

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);
}

截獲的異常以下:spring

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

content: {"type":"http://httpstatus.es/404","title":"未找到資源","status":400,"detail":"這裏是詳細的異常信息"}  -> code

cz.jirutka.spring.exhandler.messages.ErrorMessage

自定義解析器:orm

@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: "這裏是詳細的異常信息"}get

此時就能獲得咱們的Rest風格的Exception了it

相關文章
相關標籤/搜索