From e71fc6ce0f004774ccd4161358a0627a00ee19d3 Mon Sep 17 00:00:00 2001
From: Paul Daniels <paulpdaniels@gmail.com>
Date: Fri, 3 Jan 2020 17:27:37 +0800
Subject: [PATCH] fix(error): Correctly encode the error message. (#145)

---
 .../src/main/scala/caliban/GraphQLResponse.scala | 11 ++++++-----
 .../test/scala/caliban/GraphQLResponseSpec.scala | 16 +++++++++++++++-
 2 files changed, 21 insertions(+), 6 deletions(-)

diff --git a/core/src/main/scala/caliban/GraphQLResponse.scala b/core/src/main/scala/caliban/GraphQLResponse.scala
index 3539aa1b84..e92fe95c52 100644
--- a/core/src/main/scala/caliban/GraphQLResponse.scala
+++ b/core/src/main/scala/caliban/GraphQLResponse.scala
@@ -16,11 +16,12 @@ private object GraphQLResponceCirce {
   import io.circe._
   import io.circe.syntax._
   val graphQLResponseEncoder: Encoder[GraphQLResponse[CalibanError]] = Encoder
-    .instance[GraphQLResponse[CalibanError]](
-      response =>
+    .instance[GraphQLResponse[CalibanError]] {
+      case GraphQLResponse(data, Nil) => Json.obj("data" -> data.asJson)
+      case GraphQLResponse(data, errors) =>
         Json.obj(
-          "data"   -> response.data.asJson,
-          "errors" -> Json.fromValues(response.errors.map(err => Json.fromString(err.toString)))
+          "data"   -> data.asJson,
+          "errors" -> Json.fromValues(errors.map(err => Json.obj("message" -> Json.fromString(err.toString))))
         )
-    )
+    }
 }
diff --git a/core/src/test/scala/caliban/GraphQLResponseSpec.scala b/core/src/test/scala/caliban/GraphQLResponseSpec.scala
index 935780f857..5067ad0005 100644
--- a/core/src/test/scala/caliban/GraphQLResponseSpec.scala
+++ b/core/src/test/scala/caliban/GraphQLResponseSpec.scala
@@ -1,5 +1,6 @@
 package caliban
 
+import caliban.CalibanError.ExecutionError
 import caliban.Value._
 import io.circe._
 import io.circe.syntax._
@@ -13,7 +14,20 @@ object GraphQLResponseSpec
           val response = GraphQLResponse(StringValue("data"), Nil)
           assert(
             response.asJson,
-            equalTo(Json.obj("data" -> Json.fromString("data"), "errors" -> Json.arr()))
+            equalTo(Json.obj("data" -> Json.fromString("data")))
+          )
+        },
+        test("should include error only if non-empty") {
+          val response = GraphQLResponse(StringValue("data"), List(ExecutionError("Resolution failed")))
+
+          assert(
+            response.asJson,
+            equalTo(
+              Json.obj(
+                "data"   -> Json.fromString("data"),
+                "errors" -> Json.arr(Json.obj("message" -> Json.fromString("Execution error: Resolution failed")))
+              )
+            )
           )
         }
       )