stream-result icon indicating copy to clipboard operation
stream-result copied to clipboard

Extend error cases

Open emartynov opened this issue 2 years ago • 5 comments

The error cases are limited to three predefined types.

I really would like to have also validation errors with my type.

Any suggestions on how it is possible to achieve this now or thoughts on how easy it would be to incorporate it to this library?

emartynov avatar Apr 02 '23 10:04 emartynov

For now, it is not possible. Please share your use-case to see if we can add a generic case to cover it.

JcMinarro avatar Apr 03 '23 11:04 JcMinarro

I thought to eliminate the number of results we have in the app. So I want to have a functional way of the signup fields validation that later leads to the network call. Something like:

validator.validate(enteredEmail)
.then {
  validator.validate(enteredPassword)
}.then {
  network.regiester(enteredEmail, enteredPassword)
}.onSuccess {
  navigateToMainScreen()
}.onError { error ->
  when(error) {
    is PasswordValidation -> showPasswordError(error.message)
    is EmailValidation -> showEmailError(error.message)
    is Error.Newtork -> ...
  }
}

emartynov avatar Apr 03 '23 12:04 emartynov

Maybe we can open our GenericError class, Allowing you to create your own Error classes, but as far as the sealed class is defined inside of the library, you won't be able to handle all error cases on the same when condition. Opening our GenericError, we can provide a new function similar to onError where the error is cast to your new class and the sideEffect is applied:

public fun <T> onMappedError(
    errorSideEffect: (T) -> Unit,
  ): Result<A> = also {
    when (it) {
      is Failure -> (it.value as? T)?.let(errorSideEffect)
      is Success -> Unit
    }
  }

Do you think it would help?

JcMinarro avatar Apr 03 '23 13:04 JcMinarro

Interesting, I never thought about opening the GenericError. Let me try it in code.

I was thinking about a CustomError generic class that is parameterised with error data. Not sure if the compiler will like it or if it will be elegant.

emartynov avatar Apr 05 '23 07:04 emartynov

I would like this feature too 🙏 I would like to define my errors 🧐

How about including a CustomError that inherits from your error and is a new type of sealed. the field can be a type T that is our custom error hierarchy.

sometimes i use Error.ThrowableError: Represents with custom exception and then casting it. other times Error.NetworkError: Represents and using the codes with enum know to do other things. but I think the best way is to be able to offer something that encapsulates our own hierarchy and starts from yours.

joseluisgs avatar Apr 05 '23 20:04 joseluisgs