architecture-samples icon indicating copy to clipboard operation
architecture-samples copied to clipboard

[main]TasksRepository.refreshTasks() might throw an exception

Open pmellaaho opened this issue 3 years ago • 1 comments

The possible exception in DefaultTasksRepository.updateTasksFromRemoteDataSource() is not handled in either repository level or in the VM's that are calling refreshTasks() inside viewModelScope.launch

pmellaaho avatar Jun 08 '22 07:06 pmellaaho

To resolve the issue in TasksRepository.refreshTasks() potentially throwing an unhandled exception, you should wrap the call in a try-catch block, either:

Directly inside the refreshTasks() method of the repository, or

In each ViewModel that calls it via viewModelScope.launch { ... }.

Recommended Fix – Handle Exception in Repository Layer Update DefaultTasksRepository.updateTasksFromRemoteDataSource() to handle exceptions internally:

suspend fun refreshTasks() { try { updateTasksFromRemoteDataSource() } catch (e: Exception) { Log.e("TasksRepository", "Error refreshing tasks", e) // Optional: you can emit an error state or rethrow a custom exception if needed } } Alternatively – Handle in the ViewModel If you prefer leaving the repository clean and want handling per consumer:

viewModelScope.launch { try { tasksRepository.refreshTasks() } catch (e: Exception) { _uiState.value = UiState.Error("Unable to refresh tasks: ${e.message}") Log.e("TasksViewModel", "Failed to refresh tasks", e) } } Optional Improvements Define a custom exception like RemoteDataFetchException to make error states more specific.

Update UI state to reflect errors for better user feedback.

Use a Result wrapper or sealed class (e.g., Success, Error, Loading) for more robust flow handling.

Summary To fix this issue:

Wrap updateTasksFromRemoteDataSource() in a try-catch.

Log or propagate the exception as needed.

Optionally, communicate failure to the UI via UiState.

Let me know if you want a complete PR-style code patch or sealed class Result refactor!

VaradGupta23 avatar Jul 16 '25 04:07 VaradGupta23