Error handling with Combine

setFailureType

Just("").sink(receiveValue: ((String) -> Void))

tryMap

  1. We declared a custom error to hold different types of errors that can come up.
  2. We declared a thresholdTemperature and a PassthroughSubject that will supply us with the temperatures. PassthroughSubjects are also Publishers underneath and you can observe their events.
  3. We put a tryMap to calculate and return the difference from the threshold. Also, we threw an error if in case the temperature is more than the threshold.

mapError

  1. We declared a custom error enum that has a static method to convert any Swift.Error to our custom error type. For the time being, we are passing .internetNotFound as the error.
  2. We called dataTaskPublisher(for:) to provide the data for our URL. The method returns us a URLSession.DataTaskPublisher which has URLError as its failure type.
  3. We call mapError to map the URLError to our app error.
temperatureListSubject
.tryMap {
.....
throw TemperatureError.thresholdReached
}
.sink(receiveCompletion: <((Subscribers.Completion<Error>) -> Void), receiveValue: <((Int) -> Void)>)
temperatureListSubject
.tryMap {
.....
throw TemperatureError.thresholdReached
}
.mapError { error in error as? TemperatureError ?? TemperatureError.unidentified }

catch

  1. We declared a function that triggers a fallback API and returns a publisher with the desired output.
  2. We used catch operator to catch the upstream errors and triggered a fallback API to give a chance for recovering from the failure.

retry

replaceError(with:)

  1. We mapped the result to a UIImage object.
  2. If we receive any error, we replace the same with a placeholder image.

I would love to hear from you

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
G. Abhisek

G. Abhisek

Software Developer(iOS), Speaker & Writer