Front end developer specialising in JavaScript and React. Experienced in all aspects of modern front end development. Passionate about making accessible, secure and performant software.
I agree. Also, if your next function happens to depend on results from the previous function, you can chain them without nesting:
functiongetAreas(){}functiongetTowns(areas){}functiongetCities(towns){}functiongetCountries(cities){}getAreas().then(getTowns).then(getCities).catch(handleError);// or inlinegetAreas().then(functiongetTowns(areas){}).then(functiongetCities(towns){}).then(functiongetCountries(cities){}).catch(functionhandleError(){});
asyncfunctiontryAll(promises,name){constresolved=[];constrejected=[];// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/allSettledconstall=awaitPromise.allSettled(promises);for(constoutcomeofall)if(outcome.hasOwnProperty('value'))resolved.push(outcome.value);elserejected.push(outcome.reason);if(rejected.length<1)returnresolved;consterror=newError('tryAll encountered errors');error.name=name;error.rejected=rejected;throwerror;}constERROR_NAME_MULTI_REJECT='ErrorMultiReject';functionhandleMultiReject(multiError){for(consterrofmultiError.rejected)console.log('Multi Error',err.toString());}functionrouteError(err){if(err.name===ERROR_NAME_MULTI_REJECT)handleMultiReject(err);elseconsole.log('Other Error -',err.toString());}functionmakeError(source,name){consterror=newError(`Error from ${source}`);error.name=name;returnerror;}consttestFn=(result,source,name)=>result?Promise.resolve(result):Promise.reject(makeError(source,name));asyncfunctionmain(){try{constone=awaittestFn('one',`testFnOne`,'ErrorOne');constresults=awaittryAll([testFn(null,`testFnTwo`,'ErrorTwo'),testFn(null,`testFnThree`,'ErrorThree'),testFn('four',`testFnFour`,'ErrorFour'),],ERROR_NAME_MULTI_REJECT);console.log('done');}catch(err){routeError(err);}}main();// "Multi Error", "ErrorTwo: Error from testFnTwo"// "Multi Error", "ErrorThree: Error from testFnThree"
Perhaps you meant something else - in which case chaining the error handlers may be worth considering:
// wrap the error with one that is uniquely named ...asyncfunctionwrapError(promise,name){try{// https://jakearchibald.com/2017/await-vs-return-vs-return-await/#return-awaitingreturnawaitpromise;}catch(err){consterror=newError('Wrapped Error');error.name=name;error.wrapped=err;throwerror;}}functionmakeChainedHandler(next,handler){returnnext?(err)=>{handler(err);next(null);}:handler;}// ... so that the appropriate error handler// to process the wrapped error can be retrieved// which calls any other chained "aborted" handlers. //functionhandleError(err){if(err.hasOwnProperty('wrapped')){consthandler=handlers.get(err.name);if(handler){handler(err.wrapped);return;}err=err.wrapped;}console.log('Other Error -',err.toString());}asyncfunctionmain(){try{constone=awaitwrapError(demoFnOne('one'),ERROR_NAME_ONE);consttwo=awaitwrapError(demoFnTwo(null),ERROR_NAME_TWO);constthree=awaitwrapError(demoFnThree('three'),ERROR_NAME_THREE);constfour=awaitwrapError(demoFnFour('four'),ERROR_NAME_FOUR);console.log('done');}catch(err){handleError(err);}}// --- Begin Demo SupportconstDEMO_ONE='DemoFnOne';constDEMO_TWO='DemoFnTwo';constDEMO_THREE='DemoFnThree';constDEMO_FOUR='DemoFnFour';constERROR_NAME_ONE='ErrorOne';constERROR_NAME_TWO='ErrorTwo';constERROR_NAME_THREE='ErrorThree';constERROR_NAME_FOUR='ErrorFour';constconfig=[[DEMO_ONE,ERROR_NAME_ONE],[DEMO_TWO,ERROR_NAME_TWO],[DEMO_THREE,ERROR_NAME_THREE],[DEMO_FOUR,ERROR_NAME_FOUR],];functionmakeError(fnName){consterror=newError(`Error from ${fnName}`);error.name='Error'+fnName[0].toUpperCase()+fnName.slice(1);returnerror;}constmakeDemoFn=(fnName)=>(result)=>result?Promise.resolve(result):Promise.reject(makeError(fnName));functionmakeErrorHandler(fnName){return(err)=>{if(err){console.log(err.toString());return;}console.log(`Error: ${fnName} was aborted.`);};}functionmakeBoth([fnName,errName]){constfn=makeDemoFn(fnName);consthandler=makeErrorHandler(fnName);return[[fnName,fn],[errName,handler],];}const[fns,handlers]=(()=>{constfnEntries=[];consthandlerEntries=[];letchained=null;// in reverse to set up the necessary abort chainingfor(leti=config.length-1;i>=0;i-=1){const[fnEntry,[name,handler]]=makeBoth(config[i]);chained=makeChainedHandler(chained,handler);fnEntries.push(fnEntry);handlerEntries.push([name,chained]);}return[newMap(fnEntries),newMap(handlerEntries)];})();constdemoFnOne=fns.get(DEMO_ONE);constdemoFnTwo=fns.get(DEMO_TWO);constdemoFnThree=fns.get(DEMO_THREE);constdemoFnFour=fns.get(DEMO_FOUR);// --- End Demo Supportmain();// "ErrorDemoFnTwo: Error from DemoFnTwo"// "Error: DemoFnThree was aborted."// "Error: DemoFnFour was aborted."
The thing is if you present code written in the manner described you have to expect to raise some eyebrows because you are ignoring error codes. Obviously you felt the need to do this - however work arounds like this are symptomatic of poor error design.
Defensive programming is messy
So messy in fact that the designers of Erlang invented "Let it Crash" (Programming Erlang 2e, p.88):
Many languages say you should use defensive programming and check the arguments to all functions. In Erlang, defensive programming is built-in. You should describe the behavior of functions only for valid input arguments; all other arguments will cause internal errors that are automatically detected. You should never return values when a function is called with invalid arguments. You should always raise an exception. This rule is called “Let it crash.”
However most runtimes don't have the luxury of letting the process die and having the supervisor deal with the crash (p.199):
If this process dies, we might be in deep trouble since no other process can help. For this reason, sequential languages have concentrated on the prevention of failure and an emphasis on defensive programming.
However there is another point to be made - not all errors are equal. Roughly speaking:
Expected errors. Errors will occur routinely during the operation of the software and therefore should be handled appropriately.
Exceptional errors. Errors that indicate that fundamental assumptions about the software and the environment that it is operating in have been violated. These type of errors cannot be handled at the local scope, so local processing is terminated and the error is passed upwards repeatedly until some kind of sensible compensating action can be taken.
Not all languages have exceptions but they have idioms for exceptional errors. Golang:
// some processingresult,err:=doSomething()iferr!=nil{returnerr}// more processing ...
Rust has the error propagation ? operator.
letmutf=File::open("username.txt")?;
i.e. for Ok(value) the value is is bound to the variable while an Error(error) is returned right then and there.
When a language like JavaScript supports exceptions the rule of thumb tends to be:
Use error values for expected errors.
Use exceptions for unexpected, exceptional errors.
So when we see
const[areas,areasErr]=awaitgetAreas();
areasErr is an expected error and should be handled, not ignored. And just because an error code is returned doesn't necessarily imply that getAreas() can't be a source of unexpected errors. When we see
constareas=awaitgetAreas();
the code is implying that there aren't any expected errors to be handled locally but getAreas() can still be a source of unexpected errors.
there is a bit of a code smell because all errors deemed by getAreas() as exceptional are converted to expected errors at the call site and then are promptly ignored. There is an impedance mismatch between how getAreas() categorizes certain errors and how the code using it treats them. If you have no control over getAreas() then an explicit anti-corruption function (or an entire module for a "layer") may be called for to reorganize the error categorization (and the associated semantics), e.g. :
the "standardized error handling function" may seem nice, but it forces you to handle each error individually, you need to check the error for every statement with if else, resulting if else tower of terror and we are back to square one
meanwhile promise.all did a better job in handling all error with one catch
There's an npm library that does exactly this. (Full disclosure: I wrote it and have been using it for a couple of years) npmjs.com/package/@jfdi/attempt
Handling errors where they occur - midstream - obscures, in use case terminology, the happy path/basic flow/main flow/main success scenario. That doesn't mean that other flows/scenarios aren't important - on the contrary. That's why there are extensions/alternate flows/recovery flows/exception flows/option flows.
Clearly identifying the main flow in code is valuable.
Whether or not an IDE can collapse all the conditional error handling is beside the point - especially given that traditionally Java has been chastised for needing an IDE to compensate for all its warts.
to implement functional try/catch
Granted Go doesn't use a containing tuple like [error, result] but destructuring still directly exposes null or undefined values which is rather "un-functional" - typically the container (the tuple) is left as an opaque type while helper functions are used to work with the contained type indirectly (e.g. Rust's Result).
Now your criticism regarding try … catch is fair …
a variable ripe for mutation
… but JavaScript isn't a functional language (which typically is immutable by default and supports the persistent data structures to make that sustainable). However it is possible to take inspiration from Rust:
If a variable has unique access to a value, then it is safe to mutate it.
e.g. for local variables with exclusive/unique access (i.e. aren't somehow shared via a closure) mutation can be acceptable.
So maintaining a context object to "namespace" all the values that need to stretch across the various try … catch scopes isn't too unreasonable:
consthasValue=(result)=>result.hasOwnProperty('value');classResult{staticok(value){returnnewResult(value);}staticerr(error){returnnewResult(undefined,error);}constructor(value,error){if(typeofvalue!=='undefined')this.value=value;elsethis.error=error;}getisOk(){returnhasValue(this);}getisErr(){return!hasValue(this);}map(fn){returnhasValue(this)?Result.ok(fn(this.value)):Result.err(this.error);}mapOr(defaultValue,mapOk){returnhasValue(this)?mapOk(this.value):defaultValue;}mapOrElse(mapErr,mapOk){returnhasValue(this)?mapOk(this.value):mapErr(this.error);}andThen(fn){returnhasValue(this)?fn(this.value):Result.err(this.error);}// etc}constRESULT_ERROR_UNINIT=Result.err(newError('Uninitialized Result'));// To get around statement oriented// nature of try … catch// wrap it in a function//functiondoSomething(fail){// While not strictly necessary// use `context` to "namespace"// all cross scope references// and initialize them to// sensible defaults.//constcontext={success:false,message:'',result:RESULT_ERROR_UNINIT,};try{if(fail)thrownewError('Boom');context.success=true;context.result=Result.ok(context.success);}catch(err){context.success=false;context.message=err.message;context.result=Result.err(err);}finally{console.log(context.success?'Yay!':`Error: '${context.message}'`);}returncontext.result;}constisErrBoom=(error)=>errorinstanceofError&&error.message==='Boom';constisErrNotTrue=(error)=>errorinstanceofError&&error.message==="Not 'true'";constreturnFalse=(_param)=>false;constisTrue=(value)=>typeofvalue==='boolean'&&value;constisFalse=(value)=>typeofvalue==='boolean'&&!value;constnegate=(value)=>!value;constnegateOnlyTrue=(value)=>isTrue(value)?Result.ok(false):Result.err(newError("Not 'true'"));// hide try … catch inside `doSomething()` to produce a `Result`constresult1=doSomething(false);// 'Yay'console.assert(result1.isOk,'Should have been OK');console.assert(result1.mapOr(false,isTrue),"Ok value isn't 'true'");console.assert(result1.map(negate).mapOr(false,isFalse),"'map(negate)' didn't produce 'Ok(false)'");console.assert(result1.andThen(negateOnlyTrue).mapOr(false,isFalse),"'andThen(negateOnlyTrue)' didn't produce 'Ok(false)'");console.assert(result1.map(negate).andThen(negateOnlyTrue).mapOrElse(isErrNotTrue,returnFalse),"'andThen(negateOnlyTrue)' didn't produce 'Error(\"Not 'true'\")");constresult2=doSomething(true);// "Error: 'Boom'"console.assert(result2.isErr,'Should have been Error');console.assert(result2.mapOrElse(isErrBoom,returnFalse),"Message isn't 'Boom'");console.assert(result2.map(negate).mapOrElse(isErrBoom,returnFalse),"'map(negate)' didn't preserve Error");console.assert(result2.andThen(negateOnlyTrue).mapOrElse(isErrBoom,returnFalse),"'andThen(negateOnlyTrue)' didn't preserve Error");
I agree. Also, if your next function happens to depend on results from the previous function, you can chain them without nesting:
Nice article overall though, keep it up :).
Yes, this would be a good approach too :)
You can have one
catchclause below allawaitsBut what if we have all the promise dependend on promise above them, and we want to handle error for each of them?
Perhaps you meant something else - in which case chaining the error handlers may be worth considering:
The thing is if you present code written in the manner described you have to expect to raise some eyebrows because you are ignoring error codes. Obviously you felt the need to do this - however work arounds like this are symptomatic of poor error design.
Defensive programming is messy
So messy in fact that the designers of Erlang invented "Let it Crash" (Programming Erlang 2e, p.88):
However most runtimes don't have the luxury of letting the process die and having the supervisor deal with the crash (p.199):
However there is another point to be made - not all errors are equal. Roughly speaking:
Not all languages have exceptions but they have idioms for exceptional errors. Golang:
Rust has the error propagation
?operator.i.e. for
Ok(value)thevalueis is bound to the variable while anError(error)is returned right then and there.When a language like JavaScript supports exceptions the rule of thumb tends to be:
So when we see
areasErris an expected error and should be handled, not ignored. And just because an error code is returned doesn't necessarily imply thatgetAreas()can't be a source of unexpected errors. When we seethe code is implying that there aren't any expected errors to be handled locally but
getAreas()can still be a source of unexpected errors.With this in mind - 4.1.3. Rejections must be used for exceptional situations:
i.e. a promise should resolve to an error value for expected errors rather than rejecting with the expected error. So when we see
there is a bit of a code smell because all errors deemed by
getAreas()as exceptional are converted to expected errors at the call site and then are promptly ignored. There is an impedance mismatch between howgetAreas()categorizes certain errors and how the code using it treats them. If you have no control overgetAreas()then an explicit anti-corruption function (or an entire module for a "layer") may be called for to reorganize the error categorization (and the associated semantics), e.g. :so that the consuming code can be plainly
Compared to the above
comes across as expedient (though noisy) and perhaps receiving less thought than it deserves.
the "standardized error handling function" may seem nice, but it forces you to handle each error individually, you need to check the error for every statement with if else, resulting if else tower of terror and we are back to square one
meanwhile promise.all did a better job in handling all error with one catch
But what if we have all the promise dependend on promise above them, and we want to handle error for each of them?
There's an npm library that does exactly this. (Full disclosure: I wrote it and have been using it for a couple of years)
npmjs.com/package/@jfdi/attempt
All approaches have their trade-offs.
The Zen of Go:
Go's errors are values philosophy is a recognized pain point.
Handling errors where they occur - midstream - obscures, in use case terminology, the happy path/basic flow/main flow/main success scenario. That doesn't mean that other flows/scenarios aren't important - on the contrary. That's why there are extensions/alternate flows/recovery flows/exception flows/option flows.
Clearly identifying the main flow in code is valuable.
Whether or not an IDE can collapse all the conditional error handling is beside the point - especially given that traditionally Java has been chastised for needing an IDE to compensate for all its warts.
Granted Go doesn't use a containing tuple like
[error, result]but destructuring still directly exposesnullorundefinedvalues which is rather "un-functional" - typically the container (the tuple) is left as an opaque type while helper functions are used to work with the contained type indirectly (e.g. Rust's Result).Now your criticism regarding
try … catchis fair …… but JavaScript isn't a functional language (which typically is immutable by default and supports the persistent data structures to make that sustainable). However it is possible to take inspiration from Rust:
Rust: A unique perspective
e.g. for local variables with exclusive/unique access (i.e. aren't somehow shared via a closure) mutation can be acceptable.
So maintaining a
contextobject to "namespace" all the values that need to stretch across the varioustry … catchscopes isn't too unreasonable:Thank you for sharing <3
Simple and powerful solution 👌
Yes, but they are promises not functions returning promises.
You just need to pass the function(Promise) references in Promise.all