How to map error in Combine

Issue #506

When a function expects AnyPublisher<[Book], Error> but in mock, we have Just

1
2
3
4
5
6
7
func getBooks() -> AnyPublisher<[Book], Error> {
return Just([
Book(id: "1", name: "Book 1"),
Book(id: "2", name: "Book 2"),
])
.eraseToAnyPublisher()
}

There will be a mismatch, hence compile error

Cannot convert return expression of type ‘AnyPublisher<[Book], Just.Failure>’ (aka ‘AnyPublisher<Array, Never>’) to return type ‘AnyPublisher<[Book], Error>’

The reason is because Just produces Never, not Error. The workaround is to introduce Error

1
2
3
enum AppError: Error {
case impossible
}
1
2
3
4
5
6
7
8
func getBooks() -> AnyPublisher<[Book], Error> {
return Just([
Book(id: "1", name: "Book 1"),
Book(id: "2", name: "Book 2"),
])
.mapError({ _ in AppError.impossible })
.eraseToAnyPublisher()
}

Updated at 2020-11-07 20:30:01

Comments