커스텀 Exception 클래스 생성

class AppException implements Exception {
  late String cause;
  AppException(this.cause);
}

래퍼 함수 (wrap function)

기존의 함수를 감싸서 원래 동작에 약간의 처리를 추가하는 함수

에러 처리와 같은 부분을 래퍼 함수를 사용해서 구현 할 수 있다.

예를 들어 datasource 클래스에 http 요청을 하는 여러개의 메서드가 있을 때, 하나의 래퍼함수로 감싸서 동일한 에러에 대해 처리할 수 있다.

카카오 플러터 sdk 참조해서 공부

래퍼함수를 사용한 에러 처리 구현 예시

ErrorApi

class ErrorApi {
  /// 로컬 db 처리시 발생하는 에러 핸들러
  static Future<Result<T>> handleLoacalDbError<T>(
      Future<Result<T>> Function() requestFunction,
      Logger logger,
      String prefix) async {
    try {
      return await requestFunction();
    } on DatabaseException catch (e) {
      logger.e('$prefix: ${e.runtimeType}: db 사용시 에러 발생 \\n', e);
      return Result.error(e);
    } on LocalDbException catch (e) {
      if (e.errorCause != DbErrorCause.EMPTY) {
        logger.e('$prefix: ${e.message} \\n ${e.runtimeType} \\n', e);
      }
      return Result.error(e);
    } on AuthException catch (e) {
      logger.e('$prefix: ${e.message} \\n ${e.runtimeType} \\n', e);
      return Result.error(e);
    } on Exception catch (e) {
      logger.e('$prefix: ${e.runtimeType}: db 사용시 에러 발생 \\n', e);
      return Result.error(e);
    } catch (e) {
      logger.e('$prefix: ${e.runtimeType}: db 사용시 에러 발생 \\n', e);
      return Result.error(AppException('Unknow Exception'));
    }
  }

  /// 파이어베이스 api 사용시 발생하는 에러 핸들러
  static Future<Result<T>> handleRemoteApiError<T>(
      Future<Result<T>> Function() requestFunction,
      Logger logger,
      String prefix) async {
    try {
      return await requestFunction();
    } on FirebaseException catch (e) {
      logger.e('$prefix: ${e.runtimeType}: 파이어베이스 사용시 에러 발생 \\n', e);
      return Result.error(e);
    } on RemoteApiException catch (e) {
      logger.e('$prefix: ${e.runtimeType}\\n ${e.message}\\n ', e);
      return Result.error(e);
    } on AuthException catch (e) {
      logger.e('$prefix: ${e.message} \\n ${e.runtimeType} \\n', e);
      return Result.error(e);
    } on Exception catch (e) {
      logger.e('$prefix: ${e.runtimeType}: 파이어베이스 사용시 에러 발생 \\n', e);
      return Result.error(e);
    } catch (e) {
      logger.e('$prefix: ${e.runtimeType}: 파이어베이스 사용시 에러 발생 \\n', e);
      return Result.error(AppException('Unknow Exception'));
    }
  }
}
/// 저장된 모든 다이어리 가져오기
Future<Result<List<DiaryLocalEntity>>> getAllDiaries() async {
  return ErrorApi.handleLoacalDbError(() async {
    await _dbOpenCheck();

    // db에서 데이터 가져오기
    final List<Map<String, dynamic>> maps =
        await _db.query('diary', where: 'uid = ?', whereArgs: [_getUid()]);

    final entities = maps.map((e) => DiaryLocalEntity.fromJson(e)).toList();

    return Result.success(entities);
  }, _logger, '$runtimeType.getAllDiaries');
}

handleLocalDbError 메서드에 실행할 함수와, 로거, ‘인스턴스.메서드’ 문자열을 넣어준다.