Skip to content

Commit

Permalink
feature: add foldCause to HttpError (#1066)
Browse files Browse the repository at this point in the history
  • Loading branch information
tusharmath authored Feb 20, 2022
1 parent e0e413b commit 2aed79e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
12 changes: 12 additions & 0 deletions zio-http/src/main/scala/zhttp/http/HttpError.scala
Original file line number Diff line number Diff line change
@@ -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)
}

Expand Down
21 changes: 21 additions & 0 deletions zio-http/src/test/scala/zhttp/http/HttpErrorSpec.scala
Original file line number Diff line number Diff line change
@@ -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"))
}
}
}
}

0 comments on commit 2aed79e

Please sign in to comment.