2017-09-26 25 views
0

我刚开始使用jcabi流利的http客户端,我觉得我错过了一些常规的错误处理例程(我相信每个jcabi-http用户都面临它)。使用jcabi-http客户端时处理http错误的常用方法是什么?

所以,一开始总是有IOException当我使用fetch()json().readObject(),我的第一次尝试是这样的:

try { 
    return new JdkRequest("http://localhost") 
      .uri() 
       ... 
       .back() 
      .method(Request.GET) 
      .fetch() 
      .as(JacksonResponse.class) 
       .json().readObject() 
       ...; 
} catch (IOException e) { 
    throw new RuntimeException(e); 
} 

接下来,当反应在没有200 OK状态,然后json().readObject()失败,出现错误“这不是你给我的json”。所以,我想补充状态检查:

try { 
    return new JdkRequest("http://localhost") 
      ... 
      .fetch() 
      .as(RestResponse.class) 
       .assertStatus(HttpURLConnection.HTTP_OK) 
      .as(JacksonResponse.class) 
       ...; 
} catch (IOException e) { 
    throw new RuntimeException(e); 
} 

有了这个时候状态不是200 OK我收到的AssertionError,这是我必须处理给它一些业务含义:

try { 
    return new JdkRequest("http://localhost") 
      ... 
      .fetch() 
      .as(RestResponse.class) 
       .assertStatus(HttpURLConnection.HTTP_OK) 
      .as(JacksonResponse.class) 
       ...; 
} catch (IOException ex) { 
    throw new RuntimeException(ex); 
} 
} catch (AssertionError error) { 
    wrapBusiness(error); 
} 

下一页时,我想不同的行为为401,403,5XX的404状态,那么我的代码就会变成这样的事情:

try { 
    val response = new JdkRequest("http://localhost") 
      ... 
      .fetch() 
      .as(RestResponse.class); 
    HttpStatusHandlers.of(response.status()).handle(); 
    return response 
      .as(JacksonResponse.class) 
      ...; 
} catch (IOException ex) { 
    throw new RuntimeException(ex); 
} 

这个“代码进化”看起来像一个共同的模式,我重塑WHE埃尔。

也许有一个已经实现(或描述)的解决方案(或Wire.class)?

回答

0
+0

我指的是代码看起来像这样可以在项目中使用jcabi-HTTP已经实现了样板。你能说明你的项目是如何完成的吗? – Rodion

+0

@Rodion我更新了我的答案 – yegor256

相关问题