Skip to content

Instantly share code, notes, and snippets.

@LeBaleiro
Created November 29, 2021 20:10
Show Gist options
  • Save LeBaleiro/7bd00b2d0d040ee234d540bb565b602a to your computer and use it in GitHub Desktop.
Save LeBaleiro/7bd00b2d0d040ee234d540bb565b602a to your computer and use it in GitHub Desktop.
Custom Either
import 'failure.dart';
class NoParams {
const NoParams._();
}
const noParams = NoParams._();
class NoResponse {
const NoResponse._();
}
const noResponse = NoResponse._();
abstract class CustomEither<TFailure, TSuccess> {
final TFailure? _failure;
final TSuccess? _success;
CustomEither({TFailure? failure, TSuccess? success})
: _failure = failure,
_success = success,
assert(failure != null || success != null);
T fold<T>({T Function(TFailure)? onFailure, T Function(TSuccess)? onSuccess}) {
if (_failure != null && onFailure != null) return onFailure(_failure!);
if (_success != null && onSuccess != null) return onSuccess(_success!);
throw CustomEitherNotDefinedFailure();
}
T? foldSuccess<T>(T Function(TSuccess)? onSuccess) {
return fold(onFailure: (failure) => null, onSuccess: onSuccess);
}
T? foldFailure<T>(T Function(TFailure)? onFailure) {
return fold(onSuccess: (value) => null, onFailure: onFailure);
}
static SuccessCustomEither<TFailure, TSuccess> success<TFailure, TSuccess>(TSuccess value) {
return SuccessCustomEither<TFailure, TSuccess>(value);
}
static FailureCustomEither<TFailure, TSuccess> failure<TFailure, TSuccess>(TFailure value) {
return FailureCustomEither<TFailure, TSuccess>(value);
}
bool get isSuccess => _success != null;
bool get isFailure => _failure != null;
TSuccess? operator |(TSuccess? newFailureCustomEither) => fold(onFailure: (_) => newFailureCustomEither, onSuccess: (value) => value);
}
class SuccessCustomEither<TFailure, TSuccess> extends CustomEither<TFailure, TSuccess> {
SuccessCustomEither(TSuccess value) : super(success: value);
}
class FailureCustomEither<TFailure, TSuccess> extends CustomEither<TFailure, TSuccess> {
FailureCustomEither(TFailure value) : super(failure: value);
}
class CustomEitherNotDefinedFailure extends Failure {
CustomEitherNotDefinedFailure()
: super(code: 'failure-or-success-not-defined-in-custom-either', message: 'Invalid CustomEither. Failure or Success not defined');
}
abstract class Failure {
final String code;
final String message;
final Object? exception;
final StackTrace? stacktrace;
const Failure({required this.code, required this.message, this.exception, this.stacktrace});
}
class InternalFailure extends Failure {
const InternalFailure({Object? exception, StackTrace? stackTrace, String? message})
: super(
code: 'internal-failure',
message: message ??
'Ocorreu um erro interno, tente novamente. Se o problema persistir, entre em contato com o administrador do sistema.',
exception: exception,
stacktrace: stackTrace,
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment