https://kotlinlang.org logo
#server
Title
# server
j

joel

10/02/2023, 6:10 PM
hi everyone, how do you use
either
for handler different errors
a

Andrew O'Hara

10/02/2023, 8:01 PM
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

joel

10/02/2023, 8:30 PM
we are using exceptions but we are see videos that recommending errors with sealed class
a

Andrew O'Hara

10/02/2023, 8:40 PM
Was there a specific question you had about them?
j

joel

10/02/2023, 8:45 PM
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

Andrew O'Hara

10/02/2023, 8:57 PM
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

Kevin Fereira Pro

10/04/2023, 5:38 AM
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

joel

10/04/2023, 6:44 PM
yeah, but the problem is how to handle multiple errors that are in different modules.