Home > Software engineering >  How to make throw in javascript reusable in try catch
How to make throw in javascript reusable in try catch

Time:08-01

I am creating an application and in its back end, I heavily rely on try-catch and throw statements. Now that I have used it so much I want to make it reusable because I am constantly repeating the following code and want to make it reusable.

I have some reusable functions and return a response with the success property. If the success is false I then throw the error.

     const someReusableFunctionResponse= await someReusableFunction();
      if (!someReusableFunctionResponse.success) {
        const errorObject = {
          status: 400,
          message: someReusableFunctionResponse.message,
        };
        throw errorObject;
      }

I know I should use the new Error('') but that's not my ask. I want to make the above code reusable something like calling a function and it would automatically throw it.

The response object format is as follow

{
   success: false/true : bool, // required
   message: 'Some message' : string // required when success false
   value: 'Any value can be object' : any // optional
}

CodePudding user response:

Use a function. Only problem it will tell you error is in function my_assert and not in the original function which will make debugging a bit harder.

function my_assert(response) {
  if (!response.success) {
    const errorObject = {
      status: 400,
      message: response.message,
    };
    throw errorObject;
  }
}

// usage:
function foo() {
  const someReusableFunctionResponse = {
    success: false,
    message: "you failed",
    value: null
  };
  my_assert(someReusableFunctionResponse)
  return someReusableFunctionResponse
}

try {
  foo()
} catch (ex) {
  console.error(ex)
}

  • Related