0

I am using Scala STTP

I have a call to an api that is constructed as this:

val request = basicRequest
 .get(uri"$fullUri")
 .headers(headers)
 .response(asJson[MyClass])

Is it possible to cast errors returned to a different case class with similar approach (ex: asJson method)

So basically I would want to add that potential cast in response body result here:

case Success(result) =>
  if (result.code != StatusCode.Ok) {
    # try to cast here
  }
  result.body match {
    case Left(error) =>
      # Try to cast here
    case Right(r) => Right(r)
  }
vukojevicf
  • 609
  • 1
  • 4
  • 22
  • https://sttp.softwaremill.com/en/latest/responses/body.html – Gaël J Feb 11 '23 at 10:27
  • 1
    More specifically, `asJsonEither` is probably what you're looking for: https://sttp.softwaremill.com/en/latest/responses/body.html#response-metadata-dependent-deserializers – adamw Feb 12 '23 at 13:18

1 Answers1

1

I believe that a conditional response ConditionalResponseAs is what you are looking for. Example of usage:


import sttp.client3.*
import sttp.model.StatusCode

// default handler if you don't have ConditionalResponse for the case
def asUnexpectedStatusException
  asStringAlwaysLogged.mapWithMetadata((r, m) => throw UnexpectedStatusCodeException(m.code, r))

fromMetadata(
  asUnexpectedStatusException, // default case
  ConditionalResponseAs( // case for BadRequest status
    _.code == StatusCode.BadRequest,
    asJsonAlwaysUnsafe[AuthErrorResponse].map(throwErrorForResponse.tupled),
  ),
  ConditionalResponseAs(_.isSuccess, asJsonAlwaysUnsafe[SuccessResponse]), // success
)

My example using asJsonAlwaysUnsafe, but it only because I have such an example at hand, you are free to use asJson.