Browse Source

Better error handling on client (#601)

yhirose 5 years ago
parent
commit
dc5f9ba164
5 changed files with 524 additions and 466 deletions
  1. 13 10
      README.md
  2. 2 2
      example/client.cc
  3. 3 3
      example/simplecli.cc
  4. 371 336
      httplib.h
  5. 135 115
      test/test.cc

+ 13 - 10
README.md

@@ -286,9 +286,13 @@ int main(void)
 {
   httplib::Client cli("localhost", 1234);
 
-  auto res = cli.Get("/hi");
-  if (res && res->status == 200) {
-    std::cout << res->body << std::endl;
+  if (auto res = cli.Get("/hi")) {
+    if (res->status == 200) {
+      std::cout << res->body << std::endl;
+    }
+  } else {
+    auto err = res.error();
+    ...
   }
 }
 ```
@@ -434,13 +438,12 @@ auto res = cli_.Post(
 httplib::Client client(url, port);
 
 // prints: 0 / 000 bytes => 50% complete
-std::shared_ptr<httplib::Response> res =
-  cli.Get("/", [](uint64_t len, uint64_t total) {
-    printf("%lld / %lld bytes => %d%% complete\n",
-      len, total,
-      (int)(len*100/total));
-    return true; // return 'false' if you want to cancel the request.
-  }
+auto res = cli.Get("/", [](uint64_t len, uint64_t total) {
+  printf("%lld / %lld bytes => %d%% complete\n",
+    len, total,
+    (int)(len*100/total));
+  return true; // return 'false' if you want to cancel the request.
+}
 );
 ```
 

+ 2 - 2
example/client.cc

@@ -23,12 +23,12 @@ int main(void) {
   httplib::Client cli("localhost", 8080);
 #endif
 
-  auto res = cli.Get("/hi");
-  if (res) {
+  if (auto res = cli.Get("/hi")) {
     cout << res->status << endl;
     cout << res->get_header_value("Content-Type") << endl;
     cout << res->body << endl;
   } else {
+    cout << "error code: " << res.error() << std::endl;
 #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
     auto result = cli.get_openssl_verify_result();
     if (result) {

+ 3 - 3
example/simplecli.cc

@@ -17,12 +17,12 @@ int main(void) {
   auto scheme_host_port = "http://localhost:8080";
 #endif
 
-  auto res = httplib::Client(scheme_host_port).Get("/hi");
-
-  if (res) {
+  if (auto res = httplib::Client(scheme_host_port).Get("/hi")) {
     cout << res->status << endl;
     cout << res->get_header_value("Content-Type") << endl;
     cout << res->body << endl;
+  } else {
+    cout << res.error() << endl;
   }
 
   return 0;

File diff suppressed because it is too large
+ 371 - 336
httplib.h


File diff suppressed because it is too large
+ 135 - 115
test/test.cc


Some files were not shown because too many files changed in this diff