0

I'm playing around with Ramda and FP with an react-project. I want to learn a bit more to write clean code with FP, and so I overthink every line if there exists a bether or cleaner way. Now I'm here with this problem and I cannot find a solution which makes me happy:

const mapErrorToErrorNode = (onUnknownError, transformUnknownError, getKnownError) => R.pipe(
  R.prop('error'),
  handleErrorIfExists(onUnknownError, transformUnknownError, getKnownError),
  R.assoc('errorNode', R.__, {}),
);

I have to pass all parameters to the inner function as arguments. Of course, this works but its just not really nice. If I'm changing the signature of the inner function I also have to change it in this function-call. One solution would also be:

const mapErrorToErrorNode = (...args) => R.pipe(
  R.prop('error'),
  R.apply(handleErrorIfExists, args),
  R.assoc('errorNode', R.__, {}),
);

Am I missing something or is this the best approach?

(for more context what I'm trying to do, you can look at this Ramda REPL.)

(and I already looked at How do I pass in multiple parameters into a Ramda compose chain?, but I do not think that this applies for my question or maybe I just don't get it)

Putzi San
  • 5,566
  • 3
  • 19
  • 35
  • 1
    Your function has no return value, so its not functional. Nor is it clear at all here what you are trying to do. You are using functions needlessly to replace control flow constructs where you gain nothing by doing so, and replicating basic Ramda functions like `prop` with custom variants. – Jared Smith Sep 11 '17 at 15:02
  • Sorry, I was wrong. All you need is the function instance of monads: `chain = f => g => x => g(f(x)) (x); of = x => y => x; ask = x => x`. Then you can create reader functions that share an argument by chaining them. I know that functions are monads in Ramda and since `ask` is just `id` you should be able to to do it with Ramda. –  Sep 12 '17 at 10:27

1 Answers1

0

You're way over-complicating this.

const knownErrorCodes = {
  'code-1': 'msg'
};

const defaultErrorMsg = 'unknown';

const mapErrorToCode = R.pipe(
  R.prop('code'), // plucks the error code
  R.propOr(R.__, knownErrorCodes, defaultErrorMsg) // gives you the message or the default
);

console.log(mapToErrorCode({ code: 'code-1' })); // msg
console.log(mapToErrorCode({ code: 'code-2' })); // unknown
Jared Smith
  • 19,721
  • 5
  • 45
  • 83
  • The last lines in the REPL are just an example-usage of the functions. This specific case can of cause done easier but I want to standardize my error-handling in react-components: handle error only if not null, handle known errors (which can be different errors, not always it has the code-prop) and for unknown errors log them and show a default-mesage. – Putzi San Sep 12 '17 at 12:04