Scala: How to do error handling on Scala STTP

277 Views Asked by At

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)
  }
1

There are 1 best solutions below

0
On BEST ANSWER

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.