I want to create an error dto with some kind of cl...
# serialization
r
I want to create an error dto with some kind of classifier of the error in question that can be used for api consumers to consistently handle errors and/or i18n-frameworks to display an appropriate error from experience the amount of errors in a domain tends to increase, so I'm thinking it should be hierarchical, and I also think there's a lot of cases where it would be nice to have a given subdomain shown from the classifier, even though it could be derived from the endpoint giving the error so what I currently imagine is something like
subdomain.error-group.specific-error
or similar. This kind of looks like it could be a hierarchy of interfaces and enums, but designing it feels... weird. So I'm wondering, has anyone approached a similar design? How do you use the types and their serialization to achieve this? Is the easiest actually a hierarchy with a single parent requirement? Or is there a better way to do this?
a
our take: Defined in common package, available to all components:
Copy code
interface ErrorCode {
    val code: String
    val message: String
}

// combined with
sealed interface Response<out T> {
    data class Success<T>(val value: T) : Response<T>

    data class Failure(val errors: List<ErrorCode>) : Response<Nothing>
}
// QOL code omitted for brevity
Service / Domain specific error defined in the relevant component
Copy code
enum class DomainXError(override val message: String) : ErrorCode {
    override val code = name

    OUT_OF_STOCK("Human description"),
    NOT_AUTHORIZED("User is not authorized to do thing"),
    // etc
}
Service interface typically looks like
Copy code
interface XDomainManager {
    fun doThing(request: DoThingRequest): Response<XThing>
}
Calling code is then “strongly encouraged” to handle error case, can switch on the specific error type or pass human readable description if applicable.
Copy code
when(val response = xManager.doThing()) {
 is Success -> // do whatever 
 is Failure -> Act based on enum, or pass description to user
}