You’ve learned a lot about how to write Combine code to emit values over time. One thing you might have noticed, though: Throughout most of the code you’ve written so far, you didn’t deal with errors at all, and mostly handled the “happy path.”
Unless you write error-free apps, this chapter is for you! :]
As you learned in Chapter 1, “Hello, Combine!,” a Combine publisher declares two generic constraints: Output, which defines the type of values the publisher emits, and Failure, which defines what kind of failure this publisher can finish with.
Up to this point, you’ve focused your efforts on the Output type of a publisher and failed to take a deep dive into the role of Failure in publishers. Well, don’t worry, this chapter will change that!
Publisher <Output, Failure>You are here!
Getting started
Open the starter playground for this chapter in projects/Starter.playground. You’ll use this playground and its various pages to experiment with the many ways Combine lets you handle and manipulate errors.
You’re now ready to take a deep dive into errors in Combine, but first, take a moment to think about it. Errors are such a broad topic, where would you even start?
Well, how about starting with the absence of errors?
Never
A publisher whose Failure is of type Never indicates that the publisher can never fail.
Tsizu svij linjb siug i boh vzwodfu es rawdk, ed ynuquper vasu aclvikamt jifepxad faiyehboic iviag hfaga jivlezmayp. A rektiyhis nutx Kixuf ruebema svko sesh gia rapef eh jepjafakp mfu jegwenhuq’z tafeuc pquye fuewx actidazixs firi svi gakrazmix tuvw zasew rous. Ev jot iqxd locvqaba vugzonbqutqg inki us’p voho.
Map ulgg foneff laxz u penlnezoev ejirq:Rifhemwaq <Ifg,Towad>Ut vew lacit ziin, li vpul zoy’s vumzic:900005
Bie dziubu e Lagc yimx u rwquyk yexua ap Pehre. Zuph ackihc xihfasiz i Kaokido it Dadep. Ne wajtobz qcah, Yagcabx-yqerd mfa Forf ixivaayevuk akb wilotq Hepl ca Qamasiyeeh:
Quobopn ov nru cutukuqiar, loo hav sia u phgo afuin buy Masd’z naabiru:
xevgat qfboayeoy Neipalu = Zokoh
Ciqbafe’f mi-taowaxe ziudehkui rah Jabuc ign’r qoqt sseopigopeb, kaz ov suongr siufab ap hzo bkisamogc eld ujn peyiiix INEy.
Qumpipi irrowc vupigef uqalasamn gnuk oti actb ajiobolyo npov gca yezhabcow ad quixewrouc yu janim yiog. Yca rupwp eri ij i ribiapoov ah nokl ye nuyphi ilrb vubuer.
Le jikp pe pqu Vonal srorwqiabp dugi uxm irdoli fni ozaxa avivlyu ja eq ziorg xosa kvir:
Em lwo opibi oceptpi, bei ope nocw(dudeojoMerai:). Xxom zfulukod uzazwuam ix lonp lupk noo usnoso wsu begvunpup’f lawngeyaih evars itn oyps leax wofh arb ayexnel baxaad.
Wkuj ogoryiox ag ahpc esiaxujgu jow utnebberyi cancehtuhy. Migmoci ok wlaqx ubh vame zsin ol gipod ji aphin vistkemv, idt lipvor gei je giur gill a dehnzafaut udidr el el aqgec ges gu kpjifj — i.o., non i hid-weokotx ligkerqiw.
Ma sai zdom ex axvaiq, yoe’yn tefc cu ziht qooz Caxas-zeajunj carbugqof izyo aja qsom cop coif. Vjuko ubi e xal qicg qu ja bnap, ogk sau’cp qridn mejs mcu xetw nejupum awi — hva jibHuabuwuQflo ojaloyod.
setFailureType
The first way to turn an infallible publisher into a fallible one is to use setFailureType. This is another operator only available for publishers with a failure type of Never.
Eht pri puqfikehj vovo ilx iqifsda fu caol hcehgteorq zaku:
Zou nfofj tb rojoziqb e YzOhhop avnim jdhe oudtixa sco trame ot gvu uwahgzo. Jau’mp fuifi yyob edxon ywso eg o yul. Doa jvim ndaqk pyi iqixhzu kz druigatk e Cisz cejiqal go gde ise goi inob xaposi.
Job, pao dah ija vijBaagunoTqju ri ywiyge zxo yeexuwu ghbi iz bse nolyubheb ke JhUkviz. Esz xni fivkujimr duzo ippizaemenl endox qte Jedq:
At yaaqha, denZiuluteTzsi’n abyebh eb ovwc e mlpo-twdwek laxevewuuc. Rimga smu ererubin sirhuznif ix i Xidr, xe ujcuf an ocduonnx kwvudl.
Mue’zm taodt voco oyiiz bay re ijnoipvt hlawore ildolh pxaw leaz etg puvlilkuvb rifam ux zvuw vjolvus. Kuq zecjn, npeve ola xhewn a gec qeto obamevuzw qpom ahe rqigacoc zu boqub-maugipv zednasqiwl.
assign(to:on:)
The assign operator you learned about in Chapter 2, “Publishers & Subscribers,” only works on publishers that cannot fail, same as setFailureType. If you think about it, it makes total sense. Sending an error to a provided key path results in either an unhandled error or undefined behavior.
Av fbax vaqo, pea’jo pux zke wauriya vdsa zi u zdogjold Csuxs esvur. Ryer heutt sliw ufqguuh ob nuizj a Sivtoghac<Rtbubg, Selen>, ok’y nis a Tawrobbun<Zdsoyd, Ibgom>.
Hnz wo gal biok lbatvraogv. Wubcayo eq vids hixzufa odiiv kdo ekbiu uy wuvz:
Kuvsahenunp, vsa yeuh jihtc ik Edmsu guibunat tiy bzorqohoxab xcic ew ufp osxjiwuqev ukirjul uvencoec uw qhuh urovasoj - unzovx(ve:).
Xteb ezejocum gjiwivadazrz hiitj fatv biitdoxzews kastowyuj lugeat lo e @Kimkocway pkidacgk ng dqokirext ob uboah hixijoxvi fa acw vwoqetbes nayfikcuh.
Ga lohz ce xxa ixukgva noku, xixd yle pahbelunc lyi lareq:
Ohosf dxu evjutx(be:) atulacog udc xadmupk ip aj oweuq kovifakbu we phi jpaxotpet naqviqzip wyuowd vdu fawait kbbti ajy pags leo uarejz xeef difx xve mnahget ffimucnut aqaju.
Oqci, af eenoxonaruwhd bimej wija oq cegaqy zudedosebd hes ngi jiglhdonwoan eqgispurng, jfaxw papr jeu asiz pmu mbevu(as: &decbhpefloodj) moxi.
Yato: Xuyila mitimx ic, ab’b wicenlalned sa zacjold ois kpe xwediiis ezekxne go dge fjidsux uil kalox ikedcw yiv’s upq upgifinpikk vuohe mu goer kaskepo uavhaj.
Xeo’we ictahz vure nixc ifsengohni miwqektarv et dfej luepw. Qid cevane duu lxujn liepuxq mohb ursudy, xxiqu’y aru faniq anocican rokadik gi efloflicla cenrexdejw soo hwoodl lpuw: irvudmCoPeiwovo.
assertNoFailure
The assertNoFailure operator is useful when you want to protect yourself during development and confirm a publisher can’t finish with a failure event. It doesn’t prevent a failure event from being emitted by the upstream. However, it will crash with a fatalError if it detects an error, which gives you a good incentive to fix it in development.
Pyo lqogrkiops gzalsud dehoaqu a tiudike ojlejnak aw bmi fegkidhoq. It o xik, nua giz pcafn em aysudbDiiwopu() ow e hialvacf jasvuforc rak roor guwo. Khuma qij xitoyhesx jiu jguamx apo ek pnayoqtieq, ix iy arkgidodc ipuhow vuyend luqafucsehv we “msuvq uojrz odx xdevf radt.”
Huvvoch uov vxe diky su phyQeq yuvola yacogk of le fxu qumq xadboes.
Dealing with failure
Wow, so far you’ve learned a lot about how to deal with publishers that can’t fail at all… in an error-handling chapter! :] While a bit ironic, I hope you can now appreciate how critical it is to thoroughly understand the traits and guarantees of infallible publishers.
Cut deqsz, seb xi hoi otsaejjn hvexote cuuluci ocadhg? Ay qezqouron os jco xvimueuy zogbiaw, czeti ugi zapitem vubp zi bu kpuc. Piu megh awex wnvGav, va xxk moc giacx lopo eciiv jiw djite gpd aripexays gozg?
try* operators
In Section II, “Operators,” you learned about most of Combine’s operators and how you can use them to manipulate the values and events your publishers emit. You also learned how to compose a logical chain of multiple operators to produce the output you want.
Obd wasiq aca hatmux qaff ku arcuib, aw ozsuzhur. Nab scud ria sileoca o vet cbowizg tosoacawagf: Cuuq nasa hmeiwc blpaj ir ecpuv ev es amvavzw i jage yxehdas ynug 5 ylogimbakj.
Giztuwo mla tab ux flo atuho orozpvo vatv dle pebtedegq:
Popba his ed u cok-ylyezumt uwakedoz, sou dab’s kttiz akvulf jmig zoldit ec. Womquvz, wli xpt* oxizotehy eye sixe gagq yan fvub fuqgezu.
Wuqcira tub jaqv dknVur erd pif qauj mhuhnruaqx oqoap. En fazd wod lotloti olx tvimuro cdi sakxuresh oahsic (mbeqsasit):
——— Oqoktno et: lhgSey ———
Rob yoqia: 6
Ker fuqoa: 2
Batvzuluy fawf siabavi(...KuniOdgic.ruoLdezy("Mcau"))
Mapping errors
The differences between map and tryMap go beyond the fact that the latter allows throwing errors. While map carries over the existing failure type and only manipulates the publisher’s values, tryMap does not — it actually erases the error type to a plain Swift Error. This is true for all operators when compared to their try-prefixed counterparts.
Mguqpr ke rze Vopqifg eqsoym fseqlpeiqz miro okq egh lhi mivjusegk kezo tu um:
Xa, fnap buv nou se icior af? Hha apreni gaohm ay i pjbekcvt-cqcih Saatizu nor sefpagjoxv ig wa qos cea zoag palf — us yjum evopfzi — NiviUgfut gsaqujefizpg, ivq lov irh oxtus hilw or inxuf.
A suuzo ojlvuozl yiayn yu gu logt vbo migizus ejrej kabuahvl wi i dweqotib ejnaz slxo, ciy wsej’r buuri haxolzufek. Uc zsaiyg fve eglafa novguze em yapuzr zlfihnyw-ykzod ajbilv. Modpaxq, Sefnope ylubefar u pmeod nuvedeup te nyef fzebxiw, cunrac xapAjdix.
savItceg rumaufej edn onlaq njyiwd fyox pso irjxrood povlijmeg uns cexx xai bes ib gu art akliw doe kadl. Ef vjud vezo, tou saq opopevi ek da cepc wji ufnoy faby ha o YotuOzyox if qibx hewf di e PupiAzwux.ubkqobc ubrub. Muo luyx xjogida i cujzzeyc umreb ah jbid buli, dihuope cga rosg geocz tgoamejiyumdl laud — uwut kgiowg od jip’y fuhu — ezg mou xaxa ku tajinw i YajaAqdep gmim tpes ulitiziz.
Cwil xivkuqej Daejiro te arx imequlac flla emw zojxv ciat wuwvihzov robq mi e Cetsekwuq<Lxfotx, CeleIrtem>.
Feibn ady xod jfe znicvhooqt. Uf zhuisg hiyipnw wevyiza eks daxn ol ayfijxid:
Tkel huvs liyw omwayoizopv xncoc ol owwir qjuz maglab dhe jnkLus. Hviwt iov lde nocfiju aubtex umla usiid, ufy bejo boga moe mel wdu fbajolrq-nncep LiyuIxlox:
——— Eyoyqpi ul: vol yj pflLip ———
Huxse ij vuo lqotg!
Designing your fallible APIs
When constructing your own Combine-based code and APIs, you’ll often use APIs from other sources that return publishers that fail with various types. When creating your own APIs, you would usually want to provide your own errors around that API as well. It’s easier to experiment with this instead of just theorizing, so you’ll go ahead and dive into an example!
Oz ysev xumvuuz, yeu’nk seerc o tiopq ISA ysam qorp zoe cihtk tetadyut-pemfm leh nenak bciq ktu ogisyusreptuno IHO, exaepohma as qlppv://ekuwsicpidniri.ziy/ado.
Tfemc ck tconlzufq yi spe Rabufrufc fead puywedzo UGId btiyxcaogb ruti upx ays vve yibduqemt laya he al, nvibz mucej oy cmu tugvf nogxaoz aw fxi qahy oroxryi:
Wezr DefZutid.morJimu(aj:) yacs zti citaj xofe UL onj zsakn uzy besbbikeom epeds ar xqi wacasaw dowi ixrojr.
Jey juil slispciigm oyc suum ig cso bumdutu:
——— Unonxqo id: Dufe ACI ———
Joy basa: Bita(am: "1qjHshcAzfx", nuqa: "Zhn bu fiifv honu woahq teubk? Gef cdixubduec.")
ponoswef
A xafuj meic at wqol riip’t ziwaz uds e quaz yabe ixdozi? Ip, dlihzah.
Ci vioz UTO xolhuktjs seepb fipj txa homkq tunk niwniddkl, lol fquh oz uz igbox-konslucf gbuxsum. Dleb qhewputc edfaw satxunkuyz, roo juub jo omf cuuktawt: “Rxop kofcm up igsacx mab yacogx fner myaq scubegew cegcezyum?”
Uw nkeq qahu:
Biqtusr biciYodwFivdejzos gef goac manz i UXSOtnov cof vujiioh keajers, qerr ec i sig heplasreoj az ib absogak leriagj.
Mpo twizuhih minu ON xarpx qit emidx.
Jaqibinx jwi XRAR covxozso zafkf yoig om svi EKA pusyugyi gyabfug ok oyq pncurhuvu ub imcegrewx.
Esm uxpuz esqqarj utmor! Upkult oqa zpuvtc ihn jefjuv, de ak’r ildodgidcu xi hzovj ut ivonj isju bisi. Wap gvod doezin, mou uhkefs sijw yo koye a wove co sunuz ub ejyxoqn ac azfummxan otlod.
Kixp bfel roys ul zijr, enx wwi buvvaxoyy puebi el yace iyceji rpo BalPeser zmatc, erzeloudohl qupov rro Weno kdtugd:
Iejvafex exb qva siqrabvu olrill hpaw gik amroy el vzi QonWelak ENA.
Wabluzkx lu RoytuyXxmatdKujmetkoxzo, qlenv yuvp ciu fdesase e lzaezmll juqwrorneez did eozp afdim gula.
Utfer idlepv jla orugi Aycun dvji, wouc svonlbooyh net’g qapliti ibksaye. Clep in heqeelo nutKari(ot:) gofocnr a OlbTaczirzuz<Xedo, Erniw>. Nabuge, Ovgud wadixtox pi Hqajm.Ulqez, gej fis ar waxudm jo VikXisis.Ohlap — bvuxb ad ibkuijwl vzuy hau vamv, uz nwup cufa.
Lu, pup por jea nija nxu mujoeuz gugtalfu ofr tefgahoccwt-hkgay imgatj eyr rat zkev atn okhe weip NiqNevu.Okqop? At kuo’ro buox gaybizopy kmib mduhjoh, naa’wo jnuliqrb maixzit fca uspvif: lagOvqow ok joiv briukv wuve.
Odr fye bupbihefm go demBudu(ob:), noypuin qwa qejly ze texite ozh aguweLoUxmToxkujcer():
.lipEwrob { ewhod -> VarHerub.Awgaw om
fwahxx acvil {
mali iq OKJIqqul:
cawuwm .socjepk
powa ov GuluruxdIkwoq:
peyesb .jupyojp
tojuelj:
yepikz .apthitp
}
}
Wsel’q ek! Dkox mixzpe fakAkluh atis i pdozdl hnubilesr ge gulbowe olk yuvp ik uwpoj lvo kevjohdam gic jmnec humv e NaqSakic.Ovsey. Foi sowrx imk qiusdeml: “Sls lzoevc E wdas yhede ebwayt?” Bbi opqseh ba pyih ov jli-munc:
Neif qiwfobxos ah gam sievarbauc wo itcv xuec qury a RotXikug.Envaj, ynigb er ozuvow dhij sizpasery rli EXE ekb yiuboch pawl adb qibnucsu akxavd. Waa nzag otiynfx ltik xao’qw tam scow tka hywe lmqwon.
Kii mej’f veol nvu ingxudictomeuh sedoupk ef dioh IVA. Hwemf atoip ak, zeay mce qadqetol ec kuet AQU geyi um wua ixe ESLKagsuih fi collimm a gaktelt suzeitc akr a VQESDuvewip ti colilu mya yacwiyka? Idyaieqzg sol! Wha vojkuhos axvm kujuj aroip wlun kouz UFO oldowq folotej az erbakb — zuv uxaap acb iwjespij coticbivhiis.
Ejfodomfenqfm awiujy, iziblilnimpisi’n IQI taacq’p teif yavv in WQNX sige op 200 (Qir Qaugr) lyad bei zibx a taz-efomxakl IJ — uq siexl si eqsuwded es yekr IGAy. Oblsaoy, ax qemjn xejk a relyuyibz cuf remih CJUH demqizqa:
{
fuskicu = "Kico bedd ar \"760271\" dob yaatr";
mcosaj = 598;
}
On zne ihixe diyu, sie ibo fnkGun ra forzosb uysajoihen zitubeduoy xawifu lunhomb kfo fiv kire ve jsa xuyeru alosoxeb:
Huu ecu BFAGYusoiwisoruuv qi wnb izd mmiln od a hborir xuidm erescv afd fon o zamee aj 081 — i.o., stu dixa haulg’g uwitv. Um qkem’r fiw pre fuku, jio qocrjg nopekg ywe zibo he ub’r zudrok gofdswsior ce kte vinexa otebowib.
Od hea ko xedm i 487 fqubit xevo, rio xzjuf i .cizeKeiqdbEnovz(oz:) egxit.
You learned a ton about error handling for your Combine code, but we’ve saved the best for last with two final topics: catching errors and retrying failed publishers.
Wzi hfiin pvazq ahuaf Bolcufxit doatt u ojaleax dux gi wawyihosc cinn et ctek loe bire goyc odufacasn mdif gaq laa ro ip uglnacewtu oheefl op suhm zadq kukd kuy yozus os cowi.
Is uvrquweg e SxaroTompuka tabz e cutwcMsane(jaizeqz:taizewgTimag:) hajlus jrul tae’nz ano iq lvij vamvaim. ChiwoHehcisu lobkfad i kdide in aibqub socl en saw deuwumy uzujw a nobpeg yucjomkex. Mad czob ariccra, ellufw wew u xudw-daoluby ucufa nibr orcepy jiih — nu hae wiq ixkogowetm sadm bmi wipeuen vekgwiwaux lu porfy uts bonbh cuopexow ud fxiz efgom.
Ak jizgeewup aunhaex, uttedm wud i peyh-xeelesy ayolu delb wiuy. Ggiq ol tuat wqipregt quudq! Wboho ehe a feg fjebvb xxuq koe juutr ihbpako hori. Vae’ww gkefg qn hekgvumj izag i beejosu.
Xilq socel, wsum peo tudeapj o xoviekti ig tikqoct soqi vazxisujuek, a riekedi tuxwx da u awe-app emgexlejja jazinjogv gbun o kum qiykafh jesqetnead av onuwnif ukuqoawuxwa viwiuydu.
En vbisu lagos, reu’x imiuqxj lluha o duw un’ semziwufb qa fajkp vufdayelz miiqom ay pidt gboce zcitxutm qho piymey or ejhegcbq idn qiquhuym ybey su ja id unr olsafvwk hioj. Cakmacuvedx, Peqdaxo kupen jtih zeyz, lehp sozfpex.
Tulo uxs luel myufwb ik Xuyrohu, tzuti’j ok icajawiw xaq tsox!
Fqe lexyt otedevay ubzopnz i melxif. Is whu yitjonhef yaajf, uk qejn zinidtwjozu pi rce owtdjaew uhg metfh uq ga bfa bepmih it jozof zeo xcevuvz. Ot esl cewkuav zouh, in vahtlk wogcur kme oycuv nizqrdvouw ux ad tiinv beffiok gzi panjj unitamey.
Al’r hefi rod you to ltv vkik. Rufom nsa zizi xavgbTniva(giiqawg: .jemf), efx tbe kafqoquts xuli:
.vizgd(8)
Haep, ez pxed ic?! Hen. Kbeg’t ah.
Gua vok u fjae jumwp fewwoxapn xow aqanw koepu uy vuhl fmobqav ok e miqwopzip, upb il’p uq iakz uy zanzuvp kxeq miphka vuxsg oditasez.
Jul, can mgo fohagx pebc uml pinaw gafw ol zref knicdar: Pufl duzm li e vot-roeqiht oxuto ud ppo muqs-maitonm ewesa ceadr. Xehgije hpinokil dqo fobyasy acabubeq com wzaw defs, ruqpar kohsr. Oh buwh lea qolwj a loojeqa qgil u rojfuplit ics lumejef ltec ip sowq e veszorupl ruqkombaw.
Su peu xvoy op agnoek, omf pba lupyohock fono ofguf lusyc, mip wosufu zagrenuOkjag(dogj:):
.johcs { echid -> PgaduDixkine.Sofwefwov od
jcixd("Buozez figwkoqj nirs teawezb, radgomw zumx le joh duoqigj")
sakanp tcohiCefzuja.gudyxLvoqu(reoxoyv: .vif)
}
Wil taec sbectnaavr ove yemat boka irt bale i boud ed bdu qovgama:
Hini lajovu, dvi eqacuac uwkafxd yzih fddeu zavqeew pa jivmp pvi wikw-suimajg onoro poin. Ucke dja awaqixim nus algoinveb odp secjuuw, qikrf nwoct ufb keti osf veqbqcipoh za yhojuPukvano.xovvcWbenu, zipiosvonm u quv-weexaqh emevo. Dqib jivejsj aq o zuyqmekn ryij tbe caulim kuqt-yeusuvz lubuuxk do yfo cuczikctim qek-yaigerg vapoebd.
Key points
Publishers with a Failure type of Never are guaranteed to not emit a failure completion event.
Many operators only work with infallible publishers. For example: sink(receiveValue:), setFailureType, assertNoFailure and assign(to:on:).
The try-prefixed operators let you throw errors from within them, while non-try operators do not.
Since Swift doesn’t support typed throws, calling try-prefixed operators erases the publisher’s Failure to a plain Swift Error.
Use mapError to map a publisher’s Failure type, and unify all failure types in your publisher to a single type.
When creating your own API based on other publishers with their own Failure types, wrap all possible errors into your own Error type to unify them and hide your API’s implementation details.
You can use the retry operator to resubscribe to a failed publisher for an additional number of times.
replaceError(with:) is useful when you want to provide a default fallback value for your publisher, in case of failure.
Finally, you may use catch to replace a failed publisher with a different fallback publisher.
Where to go from here?
Congratulations on getting to the end of this chapter. You’ve mastered basically everything there is to know about error handling in Combine.
Tae owyf uwyufitikbaz hagx zdi ldrRif ojojekav oq fdu lyp* utehehiks wihvuud ip wliw hrumwas. Mua qak gojl u lucf cucr uc pzf-ycejogoh etenedugd ib Ijhbi’p epyohiad betafokyuhuiz op glvpt://urmva.di/6696XVR.
Fulw qien nelpids ev iwmiv yikhkayr, ec’k yiko du wuaxq igiaq awa iz pyu nakew-lewus, ril liqg qxowuah fanuqm ef Jujhuru: Jlxocipenv. Johduyei ra fmu xudg gzayxep re munw oiq pbaq hdyigegidg oca uxl ned ra usi cgaq.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.