2

I have a pure function that looks like :

function foobar(str) {
   let newStr;
   // code that depends on str and forge a new string
   ...

   return newStr;
}

Now, I would like to raise an error if str is not as expected.
My error will be a simple object like { code: 'foo', msg: 'bar' } and I'm searching for the proper way to return this error from my function.

I'd like to avoid exceptions and promises (as they are asynchronous) and ideally, I'd like this function to adopt a functional programming style.
Any clue?

Guid
  • 2,137
  • 2
  • 20
  • 33
  • Use exceptions `throw { code: 'foo', msg: 'bar' };` – jcubic Jan 12 '16 at 13:43
  • So are you just trying to return an object, or actually throw an error ? – adeneo Jan 12 '16 at 13:43
  • Possible duplicate of [Custom Exceptions in JavaScript](http://stackoverflow.com/questions/464359/custom-exceptions-in-javascript) – Jon Koops Jan 12 '16 at 13:44
  • @jcubic I don't really like exceptions but if there are no other choice... – Guid Jan 12 '16 at 13:52
  • There's always an option, if you don't want to throw, just return `false`, or an object, or whatever, and just check if the returned result is a string wherever you're calling the function. – adeneo Jan 12 '16 at 13:55
  • returning dynamically one type or one other type is out of questions for me. I prefer exceptions in this case. – Guid Jan 12 '16 at 13:57

1 Answers1

3

If you need to avoid async and typical error handling, you need your function to return an object instead of just a string. The object can have properties

var returnObject = {
    error: false,
    value: "the string",
    errorValue: "OK"
};

Then every time you call the function it needs to check the condition of returnObject.error first:

var getStringObj = foobar("string input");
if ( getStringObj.error ) {
   // probably display getStringObj.errorValue
} else {
  //normal handling
}
Steve Seeger
  • 1,409
  • 2
  • 20
  • 25