GetStream / stream-result

🚊 Railway-oriented library to easily model and handle success/failure for Kotlin Multiplatform.
https://getstream.github.io/stream-result/
Apache License 2.0
104 stars 1 forks source link

Extend error cases #3

Open emartynov opened 1 year ago

emartynov commented 1 year ago

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?

JcMinarro commented 1 year ago

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

emartynov commented 1 year ago

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 -> ...
  }
}
JcMinarro commented 1 year ago

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?

emartynov commented 1 year ago

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.

joseluisgs commented 1 year ago

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.