简体   繁体   中英

How to make throw in javascript reusable in try catch

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
}

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) }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM