scala/basic

Error Modeling (with Exception)

wefree 2023. 1. 16. 10:55
import play.api.libs.json.{Json, OFormat}


sealed class HttpError(val status: Int, val message: String) extends Throwable(message)

object HttpError {
  implicit val jsonFormat: OFormat[HttpError] = Json.format[HttpError]
  
  def apply(status: Int, message: String): HttpError = new HttpError(status, message)
  
  def unapply(err: Throwable): Option[(Int, String)] = err match {
    case err: HttpError => Option((err.status, err.getMessage))
    case _              => None
  }

  final case class BadRequest(msg: String = "Bad Request") extends HttpError(400, msg)

  final case class NotFound(path: String)
      extends HttpError(404, s"""The requested URI "$path" was not found on this server""")
}