Mapping Errors |

Operators such as tryMap erase any error types that are encountered during execution of the code within the operator. The mapError operator lets developers maintain knowledge of errors encountered, passing them down the Combine pipeline.

This is a companion discussion topic for the original entry at

hi!! there is only this part i dont understand
$0 as? NameError ?? .unknown
if $0 as? NameError fails. how come it becomes .unknown?
unknown is one case of NameError. it is not another error Type
maybe i need to review enums , and errors handling
great tutorial by the way :slight_smile:

@pedromayo This is quite a tricky one to get right because of the way in which the Combine framework behaves error wise.

You first of all use the setFailureType(to:) instance method to set the error type of the Just<String> publisher to the NameError type in case it fails since the Just<String> publisher always returns a value of some sort whatsoever and never normally fails on its very own no matter what.

You can read even more about setFailureType(to:) over here:

Then you go ahead and use the tryMap(_:) instance method to throw the NameError.tooShort(String) error. This works now since you already set the Just<String> publisher error type to NameError in the previous step, so all is good so far and up to this point.

Feel free to check out even more about tryMap(_:) over here:

The only problem over here is that Combine does not actually know anything at all about and can definitely not tell anything at all regarding what type of error you throw exactly with tryMap(_:) at this point. It can be either any kind of error type out there or even no error at all after all from its point of view. On the other hand, the Just<String> publisher can only fail with NameError errors no matter what, so any other error type you throw from tryMap(_:) results in a compiler error because of that.

In order to fix this, simply just convert the error type thrown by tryMap(_:) to NameError with the mapError(_:) instance method and you are finally good to go. You either do nothing if the thrown error is already a NameError one or replace the thrown error with NameError.unknown if it has a different error type. You may use type inference for the NameError enumeration case since the Just<String> publisher definitely knows that it can only fail with NameError errors in this case.

You can check out how mapError(_:) actually works under the hood over here:

Please let me know if you have any more questions or other issues about the whole thing when you get a chance. Thank you!