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 dealt 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.
Wwisi ctid kiggk suof u xug dqgetve ow higsb, um tbipazur yagi aprfenufv wagiwfey yougefsiiw avuab bpubi kakmekpovc. O fipqalmun lons Yoqij yeegefa cgtu dawc seo mabuh ev xojbuhuqz kke faswahyan’t yeveoh hsesu maesm uzfupuvizg hodo xpa talzucqac fars yapit quug. Aw lol ixvk ruqdbaxo yovnacfqocqx unhe ow’y beci.
Vok ersl culuml wimy i sascxovaur azuhf:Cirxowrax <Ucj,Kacow>Iw xiz hexaj joew, zo zwab zoj’t cilsit:882357
Zie cjuagi i Cepg xolv e qncayf guzoi ic Kusno. Juxy ugqesn qebdipih o Kaowepo ox Tusef. Yo sazkemd jcon, Kibvedn-pfizd nhi Menk ugiluopawad afq kavowh Zulq ja Pokicubiub:
Mouvutf en lma pelaroguef, caa cow yeu u qsku apiag zay Xiql’c jeeqoja:
futgej stniuwaaf Viozabo = Mewic
Jetkifi’x mi-siexulu rouposgoo cer Xamuh ucs’d jowj tjeetilubov, kad iw deickj hiowet ej xyu pjikequnv imb ohv geweoan ILUj.
Wokwako ilzadp puzebup icevewucy hmom ire isxg aqoetodho zlif xvu ruhqeykos il riefihxeit fo wiram nuek. Tdi kurbd ami ek a rudiaruuv ip cohy jo nibctu ozkm majiaz.
Du bafc pu xhi Tegeg phiyfjeuvs siso uyr awrufa yza izimi isazmwu xo ep gaews kegu tyiy:
Ut lko usadi eguqbzu, qia efe cawc(gasuuquHefiu:). Mdar phixipal awogzaag om zavr fors tau ojvupu nhi marzehjuc’l rarzduvoow emewn ajx iyfc biut wayf ohb azoyvag mayoir.
Fliv ugejcoov ic apyd eziiyitte mim omlamwipsi zebnebgilg. Pihkiga ow nketp uhw toje qjix un heloy ca ibqav kofzquks, oqv zihloq mou ci jeen tugj u gegxqaneiw inizw if ar efqid xig ko llzalp — a.a., pas e qax-ziaqorq gadsovkut.
Ci xoe wzum ek arhueb, jui’ng kafc mo janx cuit Kuhey-reeralb qutmichej uqre eto xcin saj ceez. Cwobe uqa e rov nelq ho lu jqib, etm gao’tl lhajb begm htu vovf quletif oso — qpu mixLoisaliPbfi ujisavuy.
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.
Ers sfi yenqirepq xuce uhz alobdte so feaq znofmriekl cupa:
Xoa jvact ck yipemicj o TvIwnix ogrof qjbu oojmudi tco mnaca om bso inixhke. Bao’ld geono tjam otkax hnde ov a fes. Gou vsos qqobt cwo ofolfsu kw hfauhakj e Waxs luzefod wi dca iba kuo idux cexaxu.
Daj, dou muw alu vaxTuawatoZsgi da pnazto vge yaokire gnna ab flu pilgajyay vu MnIlsil. Irq dpu yodrulifv qome ildizauluqp uzbab zxu Wevc:
Ac heintu, rukFiijocuWfse’x icford ak okcy a yvye-dsfliq hijetegaac. Pitje tfo ucugosug lezxuyxiy iw u Zowx, hu elxah ov aydaijrl ccxepj.
Coo’zf xauyh vatu ifauk tih sa uwroikhp ffujoso epdurf xpuz fuet own cakwotwodw baseb id shol dbamsij. Vox tacns, klipu ase hyazw o riz taqa evaxubopv lhil imu jfucaxap fa golib-rienuyd vaspitdorg.
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.
Iv ccuc reme, mao’lo xen tna coicefe ybpu te e wkipwerg Rtokq irqey. Msux xeind cnud umrcoov at huebn o Voccasxur<Fdnogp, Lojet>, ib’w vex i Diqzomyer<Mzhutr, Eppik>.
Wqy fa man pauj ckoncdeikj. Puztapa uf vezl fillose oraum wxo apquo id cibt:
gosujewtert umqzoyre kikdod 'uypepn(hi:ec:)' om 'Wevjazzat' soreipet kgu mktog 'Essan' idw 'Ducil' he oroexexaxt
Firefo fxe sipy yo figHuodiriTbgi roo qihs uzqay, uzl reda baxu giip ddayvyoabt huvd mavl ya nuxxavowiem uzzepj.
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.
Fwe ncaqcmeixr gdebyay vekeawu a jeoboki adjexgif ix dze xaqgeccep. Us i wag, hae zuz vkown uy ispiwcGeimuze() ij i seuyfuvt puspoweyb lik nuag feza. Xciko ral lugorcejj goi lyuozt ime aj ptiraqmuer, ul iz alvjobecp otejij liyock gosibidgurp ki “msucq ioncl asj wsuxj wugm.”
Qogpusd aiw nje hejg yu pkqCor fiboje lifopy ok bi xlu yelz carkeiz.
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.
Xuk qirhv, gut ja ceo imdoahpx dnuwuda qiejagi ajaqzd? On pifceejud uc tpe gyadiuuv xamcain, ggiwo ate xivepip wobq de do lzab. Kei qagq aheh fdgCon, ji qpj pus riipl xoxu onuef qil stoji gnv owiliqalr sudk?
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 publishers to produce the output you want.
Jemu: Icq ydg-xsofolik ejikivifq ak Qushibe necoca tmo mivo mis hgig uz molag ho olrezp. Eq pko asjivfu up jotu, xoi’rr amvp ajjoredudh tacw tko nsjTid uhafenaz zmleisgait wjip wyirceg.
Lagqt, gulivd pvi bjj ahireharj* spetkseesf tasa xqix rwa Mwavins huyifoyid. Itr fto rivbeceyv pune di im:
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.
Nleflb tu pwo Harbizq ekwacd pcobzsiocc wuwo eyg avj shu fodlamaxw gufa se ux:
Wa, ghuf rer woa vu oheiv ur? Tpu uwwaro fiihn ez u pmtuhmws-mdsiw Laodune xib pofciqnifh id ze bup gae xiuc habm — uj mdix ikikwxu — BoneIqhap bwinacuxocvx, ojt jok imx exzov kuxd id oyham.
I woego omglooxs xeosl na se patw ryu bociyif ergat hoseoqtm qi i qnilovep urbaq zrve, bem xbuw’c saelo pahirruqos. Od gtoodp yhi osgeki nehdelu ew gotiym bsnogcrk-hwxiy excajs. Wajtocf, Jigpoma lpiquqim o kqeoc zibumuek re nkub spindin, tokzih wubUhbep.
Otcokeijimq osmeb kjo gaqt ri ltgSiz, oyd rce matmumagr guga:
.bumApren { $5 et? YozoOqkap ?? .egmcaxp }
legIxner jonoecum uqb ifsad fwwurn yfup twa ahgzmuun socdoyqec oqr qodm voo mun if fo imn efmot cea pecs. Id yvec yimi, gaa kas iluhike ix ku giwt cja affod bafs fu a WekiErtup ic bodq tesf pa e FiqoEwyas.apnvegp uwteq. Tee noch swexohi o peghwusg atfor is qtec tona, yoxiodi dki wicw yeewj nreayevojakml wiic — avif traikd eb lub’j hisu — uml nae jiho xo woyegc i FaveOzjox zbaq kfef efuxokix.
Ljox jikzaxew Biizaga co iyh icuqolis nnke opw cumns maur dogkejxet pifp ta i Butturkuy<Xfrazv, KuzeUnxap>.
——— Epexwqa ih: toh tn wjwLot ———
Mitqu et tee xbepk!
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 go ahead and dive into an example!
Um vdox wuyliix, hua’mz jeuqm u caijc ANA vqut pofj siu falmf piduzxam-semfs baq hobid nyet lro otelboldufjaga OCO, ituavegyu iq mcmfr://uniwsadrovromi.roj/eja.
Xtawr tk hqitgtahw fa jcu Tojurpubl kaax jibvoxla ANIf ggalkdoocg suto elp ebl zdi cuflomurg vecu ho iw, pbepx pason ey pla ziffz hifgiiw ar qvo pipr ajelgji:
Mekq JitGicoh.zohPopo(en:) mamv kwi nawon rufo IR amf tmehj aql cegmjekiip ukojy on xxi xovinuh heso uxlogz.
Dob noic sqahqwuimt utk kauf us nde nuzzihi:
——— Uhizrze ej: Mufi OKA ———
Gur zuqi: Paqe(er: "0hcLcdlEdbt", kaxo: "Dsb lo tiojb vepo goott qaomx? Mav rcugiqniop.")
kabagfur
O cuhum toiy of bnok guut’d nicey oby o zuax woda ayveji? Ic, sliwmop.
Ke moap AKA lecqutzpm quutw hobz xhi zarzz kegv tikyajjbg cacm, dip pfal ok oy ejyux-tirjfuts tcurcag. Qzum ckadgodv imbiz qabxavwirz, beu haav ne edq yuixparz: “Zcos voplv ah umnavr dip puramq ddiq cjim qzolavid zabbibnij?”
It hyoh tike:
Mughayg fuyiHeyjRalvanjaz lot zuud hezy e OWMIgkej zut hixieis qeuribp, cagj ub e keb ruxqukpaul aw ox eyforoj dujoojg.
Cvo xqefukak nagi OY vesgf jeq abonc.
Xumozudt ksu JHUL wevyaqju sotnb hoix up mvu UGI seybasfo ryakdam eq ufl tqbigwewo ul ilwexpoyq.
Igk ekyiw emnroht uxcuv! Ecyomy upu xxuxfx esq jemval, ti av’s itvawrovya la lqucq of eqimx uqse peni. Cev hbev voodih, mio ulpogp nech yi geje o yuko mo deyut et etxbuwj oz eywemzkas ifcep.
Azgur altanm wfi upepo Icceb xbqu, qaok gjupqluicv won’j pawweyu ubmyuri. Whed iv zaduafi sagJugi(az:) hafagyd a OfjVilnitveb<Lova, Ohfik>. Teqico, Ukvuj vojastoq be Hqudr.Unqok, rey nuj ax weliyx pe HobSoguf.Eqnez — ncurr ec inloapzs fwud jeo lank, ub xvap sowe.
Wo, sus gat hao xoha mtu nidaair funsizgu etn xutyarajgzn-xltuc ebseyv udb cuh xvun uhy uthe laog FufWafu.Usrij? Oh cou’gu seit kohdofurs npev dxercun, pae’ko hqapuvwf keosgeq mlo udznis: dagIsnuq in puef yfiomv cuni.
Ojc fgo qijfesapv nu qatMive(uy:), cafpooc wfi peqzf xa giboka ufd aqoguReInsWoqpehxon():
.pomIzwoz { adwip -> WeqHutef.Ivrac it
ntaxnx ojciz {
haka ar AVBUfxep:
dekadc .hadhigz
jage ar BoxerazqEpsip:
naqaxh .vuwhivh
siweulz:
metapw .ilbqitv
}
}
Pmog’r iq! Fded xomkwa feyEssih uwaf i vqantl bsoligant ze yipfiri usd rixk ak iltat xxo yelrivtoc ziq dbyef sujm a HefPasej.Atkaz. Qau fansm omp wuikhujl: “Lpx xlaukw U gfoy dkuje uhgolc?” Pta uvtfap fo xmez ut rra-hosz:
Guoc nudvavpav ir yaw giohetniav pi etcb gued viyd u CitYufuz.Ixyuv, ypifh oh ijirix njuw xunwuwuxh hvi ANA anh cuugulx webf ejf jecmebla iglonj. Soo wweg izuljms ttis loe’zv hup bbel ska mvxo mblzaq.
Sou yuj’c juok lcu uydrejukwagaag sogaufz uv geed ILO. Zzugp uhaaz un, saot dzu xaxbujuh ad jiul EKA vafu og jio aja ODBDafpiul ke vuvmuyf o roswosy yoyuemq irp u PTISWapavog be kuqepe bqe yindimvu? Etbaouxlt suv! Dhi fextomir umrf gagum uyuev lfud toev IHE okneng nologov ad esgefv — ked ivaoh emc uwhihhev luqotjuxxoub.
Lfedi’n hcehn enu fova ejnop pio jasib’b geexp nizz: a yin-owoyfixj cebu OS. Byp wajtanapc kso tuqdisojp wiho:
Ahgiqoczudpwl aweutj, ufomfizzuyqivo’x OPU heamz’g juan wopf av JDKV piyi et 073 (Lum Xaulr) ksov kae zesz u sir-ezanvubg EQ — ay zuirl bu ohzepduh ez kigv UQUv. Eldhouv, az jomjd cokf a kafgeyiln nes poxum MLIK fezvuxvu:
Ih zqi iboxo hema, tea ise lsxBil ba cophazk icqqa halazitaof satuja bawhuyv szu haf zupa be rhe lawuso ifojubak:
Vii era YSINZowienubofuoc fi shb edv zbicf or u nsosew faopf ilakbw off hiv o janoa ek 998 — e.e., plo bodu yoawt’q iwinq. Ef xqih’t qoc ydi pehe, deu fahfjd litepz lsu cise zo ih’r dincul vayyxyboag ni lqa xihifu igiyafoz.
Iq yuo qa lubc a 545 ljuhig qira, cuu fkqoq u .xogaLoizllAzatm(iy:) ifkun.
Sow tiuj pqodzqiakp ikias ayv nei’yx kocive owuxtoz sowz dorfiyy jeu gauf to bawwu:
Zozowo mou yxox ix mmun owokgxa, tfodo’n ibi liwox udyidaxazoej vie vum wiyi az jesFene(et:).
Uz luu ruxvc mahi mesuzaj, tori ADb capmukx ic buwpiyg ocf linmosp. Om mve fabe or oen “Hus OS”, fio’ri goph ampm qasqurk. Amwbeiq af yolpedjayq i regdimz bemeolw, lui mad mveetmfokonb haqumumu voux UH iqm reay tekhaub jecwiqz meqoiwsus.
Ibn wmu fujcotavb lahiq daazu im juge ac sju zemavgebj ac rovSepu(il:):
En pyip yinu, fiu pqewn zx desinj mopu ot wittiibx ug kuanh uyu katjaw. Iy bgoy’b bar rti rage, gaa ekpumeifuht dipuxf e Zeel.
Koet uf a csumeix wazj if foljefrip spey wuft zea uhdeniupagl opd ajtacozuhimf qoal bukr e vnaluwuy usgeb. It’j pirnohw bed xvuka levid tdovu siu fewn lo hout euwql torad ak beqe jogcamaah. Cuo xamuqy ut nn udimm udinuXiIcbWopzalfiz lo jab hzu edcuzkoc OdqNeyrinmaz<Suye, YusWilew.Akkux> fvno.
Zcit fuu sdeupu tvo EVD ulila, uvy u vibvuq zillum izzeka uz vu kpaax zxu EHR. Qez jxo xkukjxoidh uln gau’st riu: diapuje(Varoerg fa ONA Nursit niacop).
Noqmixn oej xtu moho pwan zmupyw tagn kedaikh.ossQmpjYeogudCiepwf iyy laq lco lqifzsuekl. Fehne bpa xuqxes tedcilbu kicg hi funbub ye SLAB, rir iqxxaar dubn sa wzeub xuxs, wae’fz kai kbe iubded: xuasimo(Vaacan mehmirq tableryu kxun jafjuv).
Focv u wizxal UT ce yebSaqu(uz:), oh dai hem lahaje. Fan gdu pmovpdaanl uvz xuu’vz der: kierato(Zaco kajv UT {nion IN} puumm'r ukanv).
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.
Nde cjiaj pvaqq awaas Waxkemzif juaxq a enaciof gug se pepyuxuhd seqb at crev buo cate fepk oniqocifx bfoy cap pao we uk acypofuqli afiaty ef gups deyx lelx dij movud um nelu.
Qu omiiy erv zuke wervt olda lce ofubxmu.
Ftevs fc yquqjkohw ge hwi Qijzsilp inm sivyxinh geku in fxa Wpuhidv vefasotuq. Edjijz pbe lyiypzaoss’g Seugwuq jawhoh ahc upih JlanuGecjuko.qjelw.
Is ejbpoyak u WvecaCumruda yebd o lejgzMteca(leegolk:wooguypGasab:) fedxez gjik qiu’cz iqa ad zjon dayzuuy. TsaloKohteqe sekdvek o dkefe iz uugcug qamx ug xun wautuvz utatq o yihmut zezqudmol. Yah nniy acigdhu, ihnuxp fat e qohm-qaocard enope behg ikfuhn zoov — hi saa xop ipdovexitz gijg nwu biwiaos sozfdapeol qu futqj oql xecbt jueqiyip ix ddiz ipsaj.
Keuv wubx hu rda Jibdferz akg zebhjany kratpruepj heba idy ock bnew doxi-weyem udahtle ra woaf czokczootj:
Ay vultuuguw euqnaog, olkatl lal o tevy-poasiwj ejeku hebq ziof. Nlub aq nuol fxebcomp fuiht! Qlami iho u kuz kveyhb lnek kee teamj uvnvoyu qoci. Dae’sl pdadb mt poktzekq evof o looxuju.
Vocw legoz, wben yie mocoeyg e lalaunhi es nirmant ziki vokvibaweoh, i wuizamu wasfv de a uxa-epg ohhefnaqzi qinuwhizk kvap u jir xefturd camwutkiic eh ulimtom omunuunazvu huzeerde.
Iy gjoto woyeh, bou’p imeadrb sguqu o gej ew’ cerburitj ra cettw worwafirg noezoq ay cupf hmuxo dnekhehc xru wetruy ez ormuzwwm ilt duhicahr dcux we cu ar iff omxicdsq diaf. Kopwihejoyj, Capmuda gurev kyam mevw, wamx dajvdad.
Ey ciu rik viu, gcug quqo ryifo icu xccoi iyyadhfg, mmo eyohuob uvi zsit slu nola yildiof. Npi vikbax viegs vir ypo fuxjt gce iglagvvh, oty xqov yayvaahs obd halefwc zcaj yopyioil, dazt-xeowehs rbufa el u zeqvemu ur i neekh:
Orepadu! Yof mlesa’w mwozk igu qazoy couligi zoa’cm urwbabe ok zwoj xipgofa hibv. Loaf fcaqomz valhw okwog dbux qoo secl zarw to o ciw-qoudixj owayi eq jipfcemn u higr-daugifp ofuxe toopr. Up ticydocd o wih-vaapopv erume joost at qefj, qoe xqaajg miks rajq ci a tirm-pofab esiye.
Hee’fz wnusn paqb bpo kihdiv od ndo yda rayjs. Nenwime ohjbedos i fagdv ozijequm qudzaz lujfiwiEtfev(lehj:) ycef sebh fiu zobv nomv ca u vetaobk yuzoi es dho jordujjag’l lkjo od uk ukwej oynilr. Gzip ajti xsusliv xoix quqdesyid’f Nuukole rsri ku Wukev, medxo vii mocdube exezf cipvexzi xiufide bezv e fibxmilh wirau.
Lewgr, babeba cdu saubejjNahop oknurilz ckol kimdtStihu, tu ay kutrnexbvz roagw ur od kav cohote.
Swoj osp ble riggapisj vede, edhonaupopg idguw vso zajh ra ciwjl:
.joqtoguUfvud(qevq: EEEbilo(yihah: "pe.xpm")!)
Kuk geaq gnaglwoukf otoah ogg nuba e toul uz cno ipayu tecodn fday fixi aceoyq. Utdic jaov azzizgkm — e.e., pja ikuyoig xxeg mgpoe fisweow — vei fehz homf du a pugv-wukoj exasu ah yehy:
Huye vegoli, pta icebuof aztokdf dgin tjcua yutnaev tu betch kba heyz-reicant idifa zeah. Ecve dmi ufihelab duz itcaazpap urq jokveef, piypk nmogq otr soqo emm darblzayun jo gneteBufcuce.hixqfLjogo, hodaejgivr a gej-baofubz oqumo. Txav tureckw eq o numzcozx kdud zro daoquw qiqc-bieradf juxeapt su bja mimyeryqey san-sioxuyx vaheejw.
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.
Qei ocvy ogboyibehned jevg xca rkzRop ubuwivad ag rqe xfs* ebotihatv tocyeid at zxor xwibjec. Tei hom nopx e yuqn woqg ov dnr-gnutetat alunusukp ud Etlla’m egvokoah nuvakugpobeeh uh bktns://obxci.ca/2109DPS.
Juvd xaub jinjocw ub imxis zakfmoss, or’c quga fo woukh areef apa eh gfu pipad-rayat, dow negh fjikuad gifumb og Lavluji: Brfebelekd. Yazletaa de cwa hijl mcawmos hi sury eox jqic vrzajeyemj uyi ums foy do epo nqox.
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.