0

I 'm consuming a REST API, When the call goes OK, this API return a 200 OK Header, Then in the body it can handle two different JSONs

{"Error": {
   "code" = 1
   "msg" = "some error message"
  }
}

Or if the data send was correct, it returns

{"code" : {
  "status" = "Your submission is ..."
  "msg" = "It is happy"
  "answer" = {...}
}

The problem is that, If I use json4s, I must known which case class to use, what should I do, Use Either[Error,Code], after converting the JValue to String and check if contains Error then Left(Error) o else Right(Code), which solution should I Take. I'm looking for a good solution, and maybe a correct explanation about that.

The problem of my aprrocach is that Dispatch gives me Either[String, JsValue] so finally I will get Either[String,Either[Error,Code]], and it seems not a good object

anquegi
  • 11,125
  • 4
  • 51
  • 67
  • Sorry, I am unclear on whether you still get back a 200 in the http response for the error case. – rock-fall Jul 02 '15 at 15:55
  • Yes when the call goes well, and it returns a 200 ok. It can return two different json the error and the code depending on the data you send and after processing it in the server – anquegi Jul 03 '15 at 06:03

1 Answers1

0

I would recommend that you use the intermediate JValue (JObject) to check for your error condition not String contains and simplify your types using Try and a sealed trait.

  1. Use the future onComplete to get to the Try type returned from dispatch.
  2. Use JObject from the JValue to check for the error field.
  3. Add a new sealed trait like ApiFooResponse and extend that trait in both case classes.
  4. Conditionally return your specific case class conversion mapped over the Try.

This will avoid the String conversion and simplify the type to Try[ApiFooResponse]. Please correct me if I have made any false assumptions.

rock-fall
  • 438
  • 2
  • 11