aboutsummaryrefslogtreecommitdiff
path: root/core/src/main/scala/com/softwaremill/sttp/TryBackend.scala
blob: 267259c7f63997dc98822a2e9a6df6e246f878ae (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package com.softwaremill.sttp

import java.net.HttpURLConnection

import scala.util.Try

/** A Backend that safely wraps SttpBackend exceptions in Try's
  *
  * @param delegate An SttpBackend which to which this backend forwards all requests
  * @tparam S The type of streams that are supported by the backend. `Nothing`,
  *           if streaming requests/responses is not supported by this backend.
  */
class TryBackend[-S](delegate: SttpBackend[Id, S]) extends SttpBackend[Try, S] {
  override def send[T](request: Request[T, S]): Try[Response[T]] =
    Try(delegate.send(request))

  override def close(): Unit = delegate.close()

  override def responseMonad: MonadError[Try] = TryMonad
}

object TryBackend {
  def apply(options: SttpBackendOptions = SttpBackendOptions.Default,
            customizeConnection: HttpURLConnection => Unit = { _ =>
              ()
            }): SttpBackend[Try, Nothing] =
    new TryBackend[Nothing](
      HttpURLConnectionBackend(options, customizeConnection))
}