My previous problem, but since many people suggest NOT using exception, I asked the non-exception ve...
j
My previous problem, but since many people suggest NOT using exception, I asked the non-exception version. Which of the following is your preferred way to define error? 1.
Copy code
sealed class QueryResult {
    data class Success(...) : QueryResult()
    object NotFound : QueryResult()
    object SomeOtherError : QueryResult()
}

// API Code
when(result) {
    is QueryResult.Success -> HttpResponse(200, "...")
    QueryResult.NotFound -> HttpResponse(404, ...)
    ...
}
2.
Copy code
sealed class QueryResult {
    data class Success(...) : QueryResult()
    data class Error(val status: HttpStatus, ...) : QueryResult()
}

// API Code
when (result) {
    is QueryResult.Success -> HttpResponse(200, ...)
    is QueryResult.Error -> HttpResponse(result.status, ...)
}
The second way is more convenient but the
Error
type is coupled with the HTTP protocol.
e
I would normally use a pattern more like
Copy code
sealed class QueryResult {
    data class Success(...) : QueryResult()
    sealed class Failure : QueryResult() {
        object NotFound : Failure()
r
Coupling your data query domain to a particular wire protocol seems to me to be mixing concerns in a way that's liable to bite you long term. Perhaps with an extension function:
Copy code
fun QueryResult.status(): HttpStatus = when (this) {
  is QueryResult.Success -> OK
  is QueryResult.NotFound -> NOT_FOUND
  is QueryResult.SomeOtherError -> SERVER_ERROR
}
I like extension functions for translations between concerns, where neither should know about the other.
👍 2