hi everyone, how do you use `either` for handler d...
# server
j
hi everyone, how do you use
either
for handler different errors
a
I usually make my Error type a sealed class and then have a dedicated function to turn it into a response. Any internal errors are just thrown; no need to have special handling for something that can just be caught and handled by the app server with a generic 500.
Copy code
sealed interface AppError {
    data class ResourceNotFound(val id: String): AppError
    data class ResourceForbidden(val id: String): AppError
    data class UserError(val messageCodes: List<String>): AppError
}

fun AppError.toResponse(): Response = when(this) {
  is ResourceNotFound -> Response(Status.NOT_FOUND)
  is ResourceForbidden -> Response(Status.FORBIDDEN)
  is UserError -> Response(Status.BAD_REQUEST)
}.body(marshaller.asFormatString(this))

routes += "/v1/things" / idLens bindContract GET to { id ->
  { req ->
    service.getThing(authLens(req), id)
      .map { Response(Status.OK).with(thingLens of it) }
      .recover(AppError::toResponse)
  }
}
j
we are using exceptions but we are see videos that recommending errors with sealed class
a
Was there a specific question you had about them?
j
According to some videos I watched, it wouldn't be possible to type the exception, and this could potentially lead to issues in the long run.
this is why I am trying to use either
a
If you
The whole point of
Either
, or the
Result
class as it's more commonly known in Kotlin, is that you don't need exceptions for error handling. In my opinion, Exceptions are only for exceptional circumstances; cases where the only thing to do with the exception is to log it and return a generic 500. For this reason, you wouldn't use exceptions as the error type in your
Either
.
k
Hi, yes I'm also using sealed classes to deal with functional errors. Exceptions, as @Andrew O'Hara said is for unexpected technical errors, for example a network issue, or any other technical issue that should be only logged on back end but never return to the consumer of your service. In this last case, the minimum information is returned: Error 500....
j
yeah, but the problem is how to handle multiple errors that are in different modules.