Error handling in Combine

Combine Senior Swift 5.1+ iOS 13+ Reviewed By Alok Singh

Predict the output

What does this print?

enum E: Error { case bad }
[1, 2, 3].publisher
    .tryMap { v -> Int in
        if v == 2 { throw E.bad }
        return v
    }
    .replaceError(with: 0)
    .sink { print($0) }
Options
Hint 1 of 1

What happens to a publisher after it fails?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: B 1, 0

Correct. replaceError emits 0 and then the pipeline finishes.

Why not the others?
  • A 1, 0, 3. After the error the upstream has finished, so 3 is never sent.
  • C 1, 3. replaceError emits its replacement value.
  • D 1. replaceError emits 0 before finishing.

30-second answer

A failure is a completion: once a publisher fails, it ends and sends nothing more. Operators like catch, replaceError and retry handle it, but they replace the failed upstream too. To keep a long-lived pipeline alive, such as search, handle errors inside a flatMap or map + switchToLatest, so only the inner request fails.

Practise saying it · 45 s. No recording, just a timer

Explain Combine error handling.

Say your answer out loud, then check which of these points you covered:

  • Failure ends the stream
  • catch/replaceError/retry
  • Isolate failures in inner publishers

Deep dive

tryMap turns thrown errors into failures.

mapError converts error types to match.

retry(n) resubscribes, which re-runs side effects like requests.

setFailureType(to:) lets a Never publisher join a failing chain.

Common mistakes

  • Putting catch at the end of a long-lived pipeline.
  • Assuming retry is free.

Senior take & follow-ups

Seniors keep long-lived pipelines alive by isolating failures in inner publishers.

Follow-up questions

Think of your answer first, then open the hint.

  1. Why does my search stop after one error?

    Show hint

    The outer pipeline completed with failure.

  2. What does retry resubscribe to?

    Show hint

    The upstream, so the request runs again.

Suggest a fix if something here is wrong or out of date.