Skip to content

Do Error objects violate referential transparency?

Ryan Garant edited this page Oct 18, 2019 · 2 revisions

To start off, Error objects themselves and the act of catching an error does not change the purity of a function. What can cause contamination however, is throwing an error within a function.

A function that throws an error is not referentially transparent because given the same input it will not return the same output. However, if you wrap a function that may throw an error like so S.encase(JSON.parse) and pass the output of that safe function as the input to a pure function, it does not violate referential transparency.

Even if the stack property on the Error object is different on your machine and my machine, passing that error as an input will not contaminate the purity because it will lead to the same output for every invocation. Said another way, the program is referentially transparent if I can replace your encased call with an S.Left of some error and it still would work.