diff --git a/zio-http/src/main/scala/zhttp/http/HttpError.scala b/zio-http/src/main/scala/zhttp/http/HttpError.scala index 1a71d50a08..144da8427c 100644 --- a/zio-http/src/main/scala/zhttp/http/HttpError.scala +++ b/zio-http/src/main/scala/zhttp/http/HttpError.scala @@ -1,6 +1,18 @@ package zhttp.http +import zhttp.http.HttpError.HTTPErrorWithCause + sealed abstract class HttpError(val status: Status, val message: String) extends Throwable(message) { self => + def foldCause[A](a: A)(f: Throwable => A): A = self match { + case error: HTTPErrorWithCause => + error.cause match { + case Some(throwable) => f(throwable) + case None => a + } + case _ => a + + } + def toResponse: Response = Response.fromHttpError(self) } diff --git a/zio-http/src/test/scala/zhttp/http/HttpErrorSpec.scala b/zio-http/src/test/scala/zhttp/http/HttpErrorSpec.scala new file mode 100644 index 0000000000..8e20a14953 --- /dev/null +++ b/zio-http/src/test/scala/zhttp/http/HttpErrorSpec.scala @@ -0,0 +1,21 @@ +package zhttp.http + +import zio.test.Assertion.equalTo +import zio.test.{DefaultRunnableSpec, assert} + +object HttpErrorSpec extends DefaultRunnableSpec { + def spec = suite("HttpError") { + suite("foldCause") { + test("should fold the cause") { + val error = HttpError.InternalServerError(cause = Option(new Error("Internal server error"))) + val result = error.foldCause("")(cause => cause.getMessage) + assert(result)(equalTo("Internal server error")) + } + + test("should fold with no cause") { + val error = HttpError.NotFound(!!) + val result = error.foldCause("Page not found")(cause => cause.getMessage) + assert(result)(equalTo("Page not found")) + } + } + } +}