Last active
March 1, 2024 01:25
-
-
Save kipsong133/935571483112fb8766b0cfecd7c714b1 to your computer and use it in GitHub Desktop.
result_type_dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Dart에서 ResultType 사용하기 | |
// 출처: https://codewithandrea.com/articles/flutter-exception-handling-try-catch-result-type/ | |
/* 1. 최초 정의 */ | |
/// Base Result class | |
/// [S] represents the type of the success value | |
/// [E] should be [Exception] or a subclass of it | |
sealed class Result<S, E extends Exception> { | |
const Result(); | |
} | |
final class Success<S, E extends Exception> extends Result<S, E> { | |
const Success(this.value); | |
final S value; | |
} | |
final class Failure<S, E extends Exception> extends Result<S, E> { | |
const Failure(this.exception); | |
final E exception; | |
} | |
/* 2. Value를 전달하는 측 코드 */ | |
try { | |
final response = await _appAPI.dio.post( | |
_appAPI.socialLogin, | |
data: requestBody, | |
); | |
final loginResponse = LoginResponse.fromMap(response.data); | |
if (loginResponse.data?.accessToken != null) { | |
await tokenStorage.saveToken(loginResponse.data!.accessToken!); | |
} | |
return Success(loginResponse); | |
} catch (_) { | |
throw Failure(LoginFailure()); | |
} | |
/* 3. Value를 받는 측 코드 */ | |
// 여기는 패턴 매칭을 사용하여 Success와 Failure를 분리한다. | |
final LoginResponse? response = switch (result) { | |
Success(value: final response) => response, | |
Failure(exception: final _) => null, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment