How to handle async errors correctly?2019 Community Moderator ElectionHow do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I correctly clone a JavaScript object?How do I include a JavaScript file in another JavaScript file?How to check whether a string contains a substring in JavaScript?How to decide when to use Node.js?How do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?

Virginia employer terminated employee and wants signing bonus returned

What will happen if my luggage gets delayed?

PTIJ: Why does only a Shor Tam ask at the Seder, and not a Shor Mu'ad?

Doesn't allowing a user mode program to access kernel space memory and execute the IN and OUT instructions defeat the purpose of having CPU modes?

What are some noteworthy "mic-drop" moments in math?

Why does cron require MTA for logging?

What is Tony Stark injecting into himself in Iron Man 3?

Which situations would cause a company to ground or recall a aircraft series?

Are small insurances worth it?

How do we create new idioms and use them in a novel?

Outlet with 3 sets of wires

Are all players supposed to be able to see each others' character sheets?

Minimizing with differential evolution

Power Strip for Europe

Why does liquid water form when we exhale on a mirror?

From an axiomatic set theoric approach why can we take uncountable unions?

In the late 1940’s to early 1950’s what technology was available that could melt a LOT of ice?

What's the 'present simple' form of the word "нашла́" in 3rd person singular female?

Can I use a violin G string for D?

Does an unused member variable take up memory?

How do spaceships determine each other's mass in space?

Can we track matter through time by looking at different depths in space?

Why does Central Limit Theorem break down in my simulation?

Can I negotiate a patent idea for a raise, under French law?



How to handle async errors correctly?



2019 Community Moderator ElectionHow do JavaScript closures work?How do I check if an element is hidden in jQuery?How do I remove a property from a JavaScript object?How do I redirect to another webpage?How do I correctly clone a JavaScript object?How do I include a JavaScript file in another JavaScript file?How to check whether a string contains a substring in JavaScript?How to decide when to use Node.js?How do I remove a particular element from an array in JavaScript?How do I return the response from an asynchronous call?










1















When making a GraphQL query, and the query fails, Apollo solves this by having a data-object and an error-object.



When an async error is happening, we get the same functionality with one data-object and one error-object. But, this time we get an UnhandledPromiseRejectionWarning too, with information about: DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code..



So, we obviously need to solve this, but we want our async-functions to cast errors all the way up to Apollo. Do we need to try...catch all functions and just pass our error further up the tree? Coming from C#, were an exception just goes all the way to the top if never caught, it sounds like a tedious job to tell Apollo GraphQL that one (or more) leaves failed to retrieve data from the database.



Is there a better way to solve this, or is there any way to tell javascript/node that an uncaught error should be passed further up the call tree, until it's caught?










share|improve this question


























    1















    When making a GraphQL query, and the query fails, Apollo solves this by having a data-object and an error-object.



    When an async error is happening, we get the same functionality with one data-object and one error-object. But, this time we get an UnhandledPromiseRejectionWarning too, with information about: DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code..



    So, we obviously need to solve this, but we want our async-functions to cast errors all the way up to Apollo. Do we need to try...catch all functions and just pass our error further up the tree? Coming from C#, were an exception just goes all the way to the top if never caught, it sounds like a tedious job to tell Apollo GraphQL that one (or more) leaves failed to retrieve data from the database.



    Is there a better way to solve this, or is there any way to tell javascript/node that an uncaught error should be passed further up the call tree, until it's caught?










    share|improve this question
























      1












      1








      1








      When making a GraphQL query, and the query fails, Apollo solves this by having a data-object and an error-object.



      When an async error is happening, we get the same functionality with one data-object and one error-object. But, this time we get an UnhandledPromiseRejectionWarning too, with information about: DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code..



      So, we obviously need to solve this, but we want our async-functions to cast errors all the way up to Apollo. Do we need to try...catch all functions and just pass our error further up the tree? Coming from C#, were an exception just goes all the way to the top if never caught, it sounds like a tedious job to tell Apollo GraphQL that one (or more) leaves failed to retrieve data from the database.



      Is there a better way to solve this, or is there any way to tell javascript/node that an uncaught error should be passed further up the call tree, until it's caught?










      share|improve this question














      When making a GraphQL query, and the query fails, Apollo solves this by having a data-object and an error-object.



      When an async error is happening, we get the same functionality with one data-object and one error-object. But, this time we get an UnhandledPromiseRejectionWarning too, with information about: DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code..



      So, we obviously need to solve this, but we want our async-functions to cast errors all the way up to Apollo. Do we need to try...catch all functions and just pass our error further up the tree? Coming from C#, were an exception just goes all the way to the top if never caught, it sounds like a tedious job to tell Apollo GraphQL that one (or more) leaves failed to retrieve data from the database.



      Is there a better way to solve this, or is there any way to tell javascript/node that an uncaught error should be passed further up the call tree, until it's caught?







      javascript node.js graphql apollo-server






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 6 at 14:39









      user2687506user2687506

      419213




      419213






















          1 Answer
          1






          active

          oldest

          votes


















          1














          If you correctly chain your promises, you should never see this warning and all of your errors will be caught by GraphQL. Assume we have these two functions that return a Promise, the latter of which always rejects:



          async function doSomething() 
          return


          async function alwaysReject()
          return Promise.reject(new Error('Oh no!'))



          First, some correct examples:



          someField: async () => 
          await alwaysReject()
          await doSomething()
          ,

          // Or without async/await syntax
          someField: () =>
          return alwaysReject()
          .then(() =>
          return doSomething()
          )
          // or...
          return alwaysReject().then(doSomething)
          ,


          In all of these cases, you'll see the error inside the errors array and no warning in your console. We could reverse the order of the functions (calling doSomething first) and this would still be the case.



          Now, let's break our code:



          someField: async () => 
          alwaysReject()
          await doSomething()
          ,

          someField: () =>
          alwaysReject() // <-- Note the missing return
          .then(() =>
          return doSomething()
          )
          ,


          In these examples, we're firing off the function, but we're not awaiting the returned Promise. That means execution of our resolver continues. If the unawaited Promise resolves, there's nothing we can do with its result -- if it rejects, there's nothing we can do about the error (it's unhandled, as the warning indicates).



          In general, you should always ensure your Promises are chained correctly as shown above. This is significantly easier to do with async/await syntax, since it's exceptionally easy to miss a return without it.



          What about side effects?



          There may be functions that return a Promise that you want to run, but don't want to pause your resolver's execution for. Whether the Promise resolves or returns is irrelevant to what your resolver returns, you just need it to run. In these cases, we just need a catch to handle the promise being rejected:



          someField: async () => 
          alwaysReject()
          .catch((error) =>
          // Do something with the error
          )
          await doSomething()
          ,


          Here, we call alwaysReject and execution continues onto doSomething. If alwaysReject eventually rejects, the error will be caught and no warning will be shown in the console.



          Note: These "side effects" are not awaited, meaning GraphQL execution will continue and could very well finish while they are still running. There's no way to include errors from side effects inside your GraphQL response (i.e. the errors array), at best you can just log them. If you want a particular Promise's rejection reason to show up in the response, you need to await it inside your resolver instead of treating it like a side effect.



          A final word on try/catch and catch



          When dealing with Promises, we often see errors caught after our function call, for example:



          try 
          await doSomething()
          catch (error)
          // handle error


          return doSomething.catch((error) =>
          //handle error
          )


          This is important inside a synchronous context (for example, when building a REST api with express). Failing to catch rejected promises will result in the familiar UnhandledPromiseRejectionWarning. However, because GraphQL's execution layer effectively functions as one giant try/catch, it's not really necessary to catch your errors as long as your Promises are chained/awaited properly. This is true unless A) you're dealing with side effects as already illustrated, or B) you want to prevent the error from bubbling up:



          try {
          // execution halts because we await
          await alwaysReject()
          catch (error)
          // error is caught, so execution will continue (unless I throw the error)
          // because the resolver itself doesn't reject, the error won't be bubbled up

          await doSomething()





          share|improve this answer

























          • Thank you for a great answer! :) I was of the firm belief that you didn't need to get messy with promises anymore, if you used the async/await pattern all the way, but I guess async/await pattern still creates promises, and if they fail you need to handle the promise-exception? Or am I understanding your answer wrong? Maybe it's just a library I'm using that is using Promises and I need to chain the calls to that library, but after that I'm "free" to rely on async/await and not chain all the calls further down? Thank you once again! :)

            – user2687506
            Mar 7 at 6:02











          • Async/await is just syntactic sugar for Promises. An async function always returns a Promise. To summarize, in the context of GraphQL, if you're calling an async function (i.e. one that returns a Promise), you need to A) await it; B) chain it correctly by utilizing return/then correctly; or C) add .catch() to it to handle errors thrown.

            – Daniel Rearden
            Mar 7 at 12:24











          • If you're using async/await syntax, you are chaining your promises. Maybe that's the bit you're missing? Either way, these sort of questions are a bit easier to answer when they include actual code

            – Daniel Rearden
            Mar 7 at 12:25











          • Okey, I will provide code tomorrow and see if I can wrap my head around it easier! Need to see if I can find a template for sharing graphql-backend code easy.

            – user2687506
            Mar 7 at 14:05











          • Okay, so I found the issue, and it simply was that I didn't know enough of javascript. It had nothing to do with Apollo-graphql to do at all. I can't really accept that workingRejection2 works where as notWorkingRejection2 doesn't work, but I guess it has to do with me not getting promises 100% yet. codesandbox.io/s/m4q8jy6lvy

            – user2687506
            Mar 7 at 16:43










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55025673%2fhow-to-handle-async-errors-correctly%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          If you correctly chain your promises, you should never see this warning and all of your errors will be caught by GraphQL. Assume we have these two functions that return a Promise, the latter of which always rejects:



          async function doSomething() 
          return


          async function alwaysReject()
          return Promise.reject(new Error('Oh no!'))



          First, some correct examples:



          someField: async () => 
          await alwaysReject()
          await doSomething()
          ,

          // Or without async/await syntax
          someField: () =>
          return alwaysReject()
          .then(() =>
          return doSomething()
          )
          // or...
          return alwaysReject().then(doSomething)
          ,


          In all of these cases, you'll see the error inside the errors array and no warning in your console. We could reverse the order of the functions (calling doSomething first) and this would still be the case.



          Now, let's break our code:



          someField: async () => 
          alwaysReject()
          await doSomething()
          ,

          someField: () =>
          alwaysReject() // <-- Note the missing return
          .then(() =>
          return doSomething()
          )
          ,


          In these examples, we're firing off the function, but we're not awaiting the returned Promise. That means execution of our resolver continues. If the unawaited Promise resolves, there's nothing we can do with its result -- if it rejects, there's nothing we can do about the error (it's unhandled, as the warning indicates).



          In general, you should always ensure your Promises are chained correctly as shown above. This is significantly easier to do with async/await syntax, since it's exceptionally easy to miss a return without it.



          What about side effects?



          There may be functions that return a Promise that you want to run, but don't want to pause your resolver's execution for. Whether the Promise resolves or returns is irrelevant to what your resolver returns, you just need it to run. In these cases, we just need a catch to handle the promise being rejected:



          someField: async () => 
          alwaysReject()
          .catch((error) =>
          // Do something with the error
          )
          await doSomething()
          ,


          Here, we call alwaysReject and execution continues onto doSomething. If alwaysReject eventually rejects, the error will be caught and no warning will be shown in the console.



          Note: These "side effects" are not awaited, meaning GraphQL execution will continue and could very well finish while they are still running. There's no way to include errors from side effects inside your GraphQL response (i.e. the errors array), at best you can just log them. If you want a particular Promise's rejection reason to show up in the response, you need to await it inside your resolver instead of treating it like a side effect.



          A final word on try/catch and catch



          When dealing with Promises, we often see errors caught after our function call, for example:



          try 
          await doSomething()
          catch (error)
          // handle error


          return doSomething.catch((error) =>
          //handle error
          )


          This is important inside a synchronous context (for example, when building a REST api with express). Failing to catch rejected promises will result in the familiar UnhandledPromiseRejectionWarning. However, because GraphQL's execution layer effectively functions as one giant try/catch, it's not really necessary to catch your errors as long as your Promises are chained/awaited properly. This is true unless A) you're dealing with side effects as already illustrated, or B) you want to prevent the error from bubbling up:



          try {
          // execution halts because we await
          await alwaysReject()
          catch (error)
          // error is caught, so execution will continue (unless I throw the error)
          // because the resolver itself doesn't reject, the error won't be bubbled up

          await doSomething()





          share|improve this answer

























          • Thank you for a great answer! :) I was of the firm belief that you didn't need to get messy with promises anymore, if you used the async/await pattern all the way, but I guess async/await pattern still creates promises, and if they fail you need to handle the promise-exception? Or am I understanding your answer wrong? Maybe it's just a library I'm using that is using Promises and I need to chain the calls to that library, but after that I'm "free" to rely on async/await and not chain all the calls further down? Thank you once again! :)

            – user2687506
            Mar 7 at 6:02











          • Async/await is just syntactic sugar for Promises. An async function always returns a Promise. To summarize, in the context of GraphQL, if you're calling an async function (i.e. one that returns a Promise), you need to A) await it; B) chain it correctly by utilizing return/then correctly; or C) add .catch() to it to handle errors thrown.

            – Daniel Rearden
            Mar 7 at 12:24











          • If you're using async/await syntax, you are chaining your promises. Maybe that's the bit you're missing? Either way, these sort of questions are a bit easier to answer when they include actual code

            – Daniel Rearden
            Mar 7 at 12:25











          • Okey, I will provide code tomorrow and see if I can wrap my head around it easier! Need to see if I can find a template for sharing graphql-backend code easy.

            – user2687506
            Mar 7 at 14:05











          • Okay, so I found the issue, and it simply was that I didn't know enough of javascript. It had nothing to do with Apollo-graphql to do at all. I can't really accept that workingRejection2 works where as notWorkingRejection2 doesn't work, but I guess it has to do with me not getting promises 100% yet. codesandbox.io/s/m4q8jy6lvy

            – user2687506
            Mar 7 at 16:43















          1














          If you correctly chain your promises, you should never see this warning and all of your errors will be caught by GraphQL. Assume we have these two functions that return a Promise, the latter of which always rejects:



          async function doSomething() 
          return


          async function alwaysReject()
          return Promise.reject(new Error('Oh no!'))



          First, some correct examples:



          someField: async () => 
          await alwaysReject()
          await doSomething()
          ,

          // Or without async/await syntax
          someField: () =>
          return alwaysReject()
          .then(() =>
          return doSomething()
          )
          // or...
          return alwaysReject().then(doSomething)
          ,


          In all of these cases, you'll see the error inside the errors array and no warning in your console. We could reverse the order of the functions (calling doSomething first) and this would still be the case.



          Now, let's break our code:



          someField: async () => 
          alwaysReject()
          await doSomething()
          ,

          someField: () =>
          alwaysReject() // <-- Note the missing return
          .then(() =>
          return doSomething()
          )
          ,


          In these examples, we're firing off the function, but we're not awaiting the returned Promise. That means execution of our resolver continues. If the unawaited Promise resolves, there's nothing we can do with its result -- if it rejects, there's nothing we can do about the error (it's unhandled, as the warning indicates).



          In general, you should always ensure your Promises are chained correctly as shown above. This is significantly easier to do with async/await syntax, since it's exceptionally easy to miss a return without it.



          What about side effects?



          There may be functions that return a Promise that you want to run, but don't want to pause your resolver's execution for. Whether the Promise resolves or returns is irrelevant to what your resolver returns, you just need it to run. In these cases, we just need a catch to handle the promise being rejected:



          someField: async () => 
          alwaysReject()
          .catch((error) =>
          // Do something with the error
          )
          await doSomething()
          ,


          Here, we call alwaysReject and execution continues onto doSomething. If alwaysReject eventually rejects, the error will be caught and no warning will be shown in the console.



          Note: These "side effects" are not awaited, meaning GraphQL execution will continue and could very well finish while they are still running. There's no way to include errors from side effects inside your GraphQL response (i.e. the errors array), at best you can just log them. If you want a particular Promise's rejection reason to show up in the response, you need to await it inside your resolver instead of treating it like a side effect.



          A final word on try/catch and catch



          When dealing with Promises, we often see errors caught after our function call, for example:



          try 
          await doSomething()
          catch (error)
          // handle error


          return doSomething.catch((error) =>
          //handle error
          )


          This is important inside a synchronous context (for example, when building a REST api with express). Failing to catch rejected promises will result in the familiar UnhandledPromiseRejectionWarning. However, because GraphQL's execution layer effectively functions as one giant try/catch, it's not really necessary to catch your errors as long as your Promises are chained/awaited properly. This is true unless A) you're dealing with side effects as already illustrated, or B) you want to prevent the error from bubbling up:



          try {
          // execution halts because we await
          await alwaysReject()
          catch (error)
          // error is caught, so execution will continue (unless I throw the error)
          // because the resolver itself doesn't reject, the error won't be bubbled up

          await doSomething()





          share|improve this answer

























          • Thank you for a great answer! :) I was of the firm belief that you didn't need to get messy with promises anymore, if you used the async/await pattern all the way, but I guess async/await pattern still creates promises, and if they fail you need to handle the promise-exception? Or am I understanding your answer wrong? Maybe it's just a library I'm using that is using Promises and I need to chain the calls to that library, but after that I'm "free" to rely on async/await and not chain all the calls further down? Thank you once again! :)

            – user2687506
            Mar 7 at 6:02











          • Async/await is just syntactic sugar for Promises. An async function always returns a Promise. To summarize, in the context of GraphQL, if you're calling an async function (i.e. one that returns a Promise), you need to A) await it; B) chain it correctly by utilizing return/then correctly; or C) add .catch() to it to handle errors thrown.

            – Daniel Rearden
            Mar 7 at 12:24











          • If you're using async/await syntax, you are chaining your promises. Maybe that's the bit you're missing? Either way, these sort of questions are a bit easier to answer when they include actual code

            – Daniel Rearden
            Mar 7 at 12:25











          • Okey, I will provide code tomorrow and see if I can wrap my head around it easier! Need to see if I can find a template for sharing graphql-backend code easy.

            – user2687506
            Mar 7 at 14:05











          • Okay, so I found the issue, and it simply was that I didn't know enough of javascript. It had nothing to do with Apollo-graphql to do at all. I can't really accept that workingRejection2 works where as notWorkingRejection2 doesn't work, but I guess it has to do with me not getting promises 100% yet. codesandbox.io/s/m4q8jy6lvy

            – user2687506
            Mar 7 at 16:43













          1












          1








          1







          If you correctly chain your promises, you should never see this warning and all of your errors will be caught by GraphQL. Assume we have these two functions that return a Promise, the latter of which always rejects:



          async function doSomething() 
          return


          async function alwaysReject()
          return Promise.reject(new Error('Oh no!'))



          First, some correct examples:



          someField: async () => 
          await alwaysReject()
          await doSomething()
          ,

          // Or without async/await syntax
          someField: () =>
          return alwaysReject()
          .then(() =>
          return doSomething()
          )
          // or...
          return alwaysReject().then(doSomething)
          ,


          In all of these cases, you'll see the error inside the errors array and no warning in your console. We could reverse the order of the functions (calling doSomething first) and this would still be the case.



          Now, let's break our code:



          someField: async () => 
          alwaysReject()
          await doSomething()
          ,

          someField: () =>
          alwaysReject() // <-- Note the missing return
          .then(() =>
          return doSomething()
          )
          ,


          In these examples, we're firing off the function, but we're not awaiting the returned Promise. That means execution of our resolver continues. If the unawaited Promise resolves, there's nothing we can do with its result -- if it rejects, there's nothing we can do about the error (it's unhandled, as the warning indicates).



          In general, you should always ensure your Promises are chained correctly as shown above. This is significantly easier to do with async/await syntax, since it's exceptionally easy to miss a return without it.



          What about side effects?



          There may be functions that return a Promise that you want to run, but don't want to pause your resolver's execution for. Whether the Promise resolves or returns is irrelevant to what your resolver returns, you just need it to run. In these cases, we just need a catch to handle the promise being rejected:



          someField: async () => 
          alwaysReject()
          .catch((error) =>
          // Do something with the error
          )
          await doSomething()
          ,


          Here, we call alwaysReject and execution continues onto doSomething. If alwaysReject eventually rejects, the error will be caught and no warning will be shown in the console.



          Note: These "side effects" are not awaited, meaning GraphQL execution will continue and could very well finish while they are still running. There's no way to include errors from side effects inside your GraphQL response (i.e. the errors array), at best you can just log them. If you want a particular Promise's rejection reason to show up in the response, you need to await it inside your resolver instead of treating it like a side effect.



          A final word on try/catch and catch



          When dealing with Promises, we often see errors caught after our function call, for example:



          try 
          await doSomething()
          catch (error)
          // handle error


          return doSomething.catch((error) =>
          //handle error
          )


          This is important inside a synchronous context (for example, when building a REST api with express). Failing to catch rejected promises will result in the familiar UnhandledPromiseRejectionWarning. However, because GraphQL's execution layer effectively functions as one giant try/catch, it's not really necessary to catch your errors as long as your Promises are chained/awaited properly. This is true unless A) you're dealing with side effects as already illustrated, or B) you want to prevent the error from bubbling up:



          try {
          // execution halts because we await
          await alwaysReject()
          catch (error)
          // error is caught, so execution will continue (unless I throw the error)
          // because the resolver itself doesn't reject, the error won't be bubbled up

          await doSomething()





          share|improve this answer















          If you correctly chain your promises, you should never see this warning and all of your errors will be caught by GraphQL. Assume we have these two functions that return a Promise, the latter of which always rejects:



          async function doSomething() 
          return


          async function alwaysReject()
          return Promise.reject(new Error('Oh no!'))



          First, some correct examples:



          someField: async () => 
          await alwaysReject()
          await doSomething()
          ,

          // Or without async/await syntax
          someField: () =>
          return alwaysReject()
          .then(() =>
          return doSomething()
          )
          // or...
          return alwaysReject().then(doSomething)
          ,


          In all of these cases, you'll see the error inside the errors array and no warning in your console. We could reverse the order of the functions (calling doSomething first) and this would still be the case.



          Now, let's break our code:



          someField: async () => 
          alwaysReject()
          await doSomething()
          ,

          someField: () =>
          alwaysReject() // <-- Note the missing return
          .then(() =>
          return doSomething()
          )
          ,


          In these examples, we're firing off the function, but we're not awaiting the returned Promise. That means execution of our resolver continues. If the unawaited Promise resolves, there's nothing we can do with its result -- if it rejects, there's nothing we can do about the error (it's unhandled, as the warning indicates).



          In general, you should always ensure your Promises are chained correctly as shown above. This is significantly easier to do with async/await syntax, since it's exceptionally easy to miss a return without it.



          What about side effects?



          There may be functions that return a Promise that you want to run, but don't want to pause your resolver's execution for. Whether the Promise resolves or returns is irrelevant to what your resolver returns, you just need it to run. In these cases, we just need a catch to handle the promise being rejected:



          someField: async () => 
          alwaysReject()
          .catch((error) =>
          // Do something with the error
          )
          await doSomething()
          ,


          Here, we call alwaysReject and execution continues onto doSomething. If alwaysReject eventually rejects, the error will be caught and no warning will be shown in the console.



          Note: These "side effects" are not awaited, meaning GraphQL execution will continue and could very well finish while they are still running. There's no way to include errors from side effects inside your GraphQL response (i.e. the errors array), at best you can just log them. If you want a particular Promise's rejection reason to show up in the response, you need to await it inside your resolver instead of treating it like a side effect.



          A final word on try/catch and catch



          When dealing with Promises, we often see errors caught after our function call, for example:



          try 
          await doSomething()
          catch (error)
          // handle error


          return doSomething.catch((error) =>
          //handle error
          )


          This is important inside a synchronous context (for example, when building a REST api with express). Failing to catch rejected promises will result in the familiar UnhandledPromiseRejectionWarning. However, because GraphQL's execution layer effectively functions as one giant try/catch, it's not really necessary to catch your errors as long as your Promises are chained/awaited properly. This is true unless A) you're dealing with side effects as already illustrated, or B) you want to prevent the error from bubbling up:



          try {
          // execution halts because we await
          await alwaysReject()
          catch (error)
          // error is caught, so execution will continue (unless I throw the error)
          // because the resolver itself doesn't reject, the error won't be bubbled up

          await doSomething()






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 6 at 16:51

























          answered Mar 6 at 16:44









          Daniel ReardenDaniel Rearden

          15.7k11642




          15.7k11642












          • Thank you for a great answer! :) I was of the firm belief that you didn't need to get messy with promises anymore, if you used the async/await pattern all the way, but I guess async/await pattern still creates promises, and if they fail you need to handle the promise-exception? Or am I understanding your answer wrong? Maybe it's just a library I'm using that is using Promises and I need to chain the calls to that library, but after that I'm "free" to rely on async/await and not chain all the calls further down? Thank you once again! :)

            – user2687506
            Mar 7 at 6:02











          • Async/await is just syntactic sugar for Promises. An async function always returns a Promise. To summarize, in the context of GraphQL, if you're calling an async function (i.e. one that returns a Promise), you need to A) await it; B) chain it correctly by utilizing return/then correctly; or C) add .catch() to it to handle errors thrown.

            – Daniel Rearden
            Mar 7 at 12:24











          • If you're using async/await syntax, you are chaining your promises. Maybe that's the bit you're missing? Either way, these sort of questions are a bit easier to answer when they include actual code

            – Daniel Rearden
            Mar 7 at 12:25











          • Okey, I will provide code tomorrow and see if I can wrap my head around it easier! Need to see if I can find a template for sharing graphql-backend code easy.

            – user2687506
            Mar 7 at 14:05











          • Okay, so I found the issue, and it simply was that I didn't know enough of javascript. It had nothing to do with Apollo-graphql to do at all. I can't really accept that workingRejection2 works where as notWorkingRejection2 doesn't work, but I guess it has to do with me not getting promises 100% yet. codesandbox.io/s/m4q8jy6lvy

            – user2687506
            Mar 7 at 16:43

















          • Thank you for a great answer! :) I was of the firm belief that you didn't need to get messy with promises anymore, if you used the async/await pattern all the way, but I guess async/await pattern still creates promises, and if they fail you need to handle the promise-exception? Or am I understanding your answer wrong? Maybe it's just a library I'm using that is using Promises and I need to chain the calls to that library, but after that I'm "free" to rely on async/await and not chain all the calls further down? Thank you once again! :)

            – user2687506
            Mar 7 at 6:02











          • Async/await is just syntactic sugar for Promises. An async function always returns a Promise. To summarize, in the context of GraphQL, if you're calling an async function (i.e. one that returns a Promise), you need to A) await it; B) chain it correctly by utilizing return/then correctly; or C) add .catch() to it to handle errors thrown.

            – Daniel Rearden
            Mar 7 at 12:24











          • If you're using async/await syntax, you are chaining your promises. Maybe that's the bit you're missing? Either way, these sort of questions are a bit easier to answer when they include actual code

            – Daniel Rearden
            Mar 7 at 12:25











          • Okey, I will provide code tomorrow and see if I can wrap my head around it easier! Need to see if I can find a template for sharing graphql-backend code easy.

            – user2687506
            Mar 7 at 14:05











          • Okay, so I found the issue, and it simply was that I didn't know enough of javascript. It had nothing to do with Apollo-graphql to do at all. I can't really accept that workingRejection2 works where as notWorkingRejection2 doesn't work, but I guess it has to do with me not getting promises 100% yet. codesandbox.io/s/m4q8jy6lvy

            – user2687506
            Mar 7 at 16:43
















          Thank you for a great answer! :) I was of the firm belief that you didn't need to get messy with promises anymore, if you used the async/await pattern all the way, but I guess async/await pattern still creates promises, and if they fail you need to handle the promise-exception? Or am I understanding your answer wrong? Maybe it's just a library I'm using that is using Promises and I need to chain the calls to that library, but after that I'm "free" to rely on async/await and not chain all the calls further down? Thank you once again! :)

          – user2687506
          Mar 7 at 6:02





          Thank you for a great answer! :) I was of the firm belief that you didn't need to get messy with promises anymore, if you used the async/await pattern all the way, but I guess async/await pattern still creates promises, and if they fail you need to handle the promise-exception? Or am I understanding your answer wrong? Maybe it's just a library I'm using that is using Promises and I need to chain the calls to that library, but after that I'm "free" to rely on async/await and not chain all the calls further down? Thank you once again! :)

          – user2687506
          Mar 7 at 6:02













          Async/await is just syntactic sugar for Promises. An async function always returns a Promise. To summarize, in the context of GraphQL, if you're calling an async function (i.e. one that returns a Promise), you need to A) await it; B) chain it correctly by utilizing return/then correctly; or C) add .catch() to it to handle errors thrown.

          – Daniel Rearden
          Mar 7 at 12:24





          Async/await is just syntactic sugar for Promises. An async function always returns a Promise. To summarize, in the context of GraphQL, if you're calling an async function (i.e. one that returns a Promise), you need to A) await it; B) chain it correctly by utilizing return/then correctly; or C) add .catch() to it to handle errors thrown.

          – Daniel Rearden
          Mar 7 at 12:24













          If you're using async/await syntax, you are chaining your promises. Maybe that's the bit you're missing? Either way, these sort of questions are a bit easier to answer when they include actual code

          – Daniel Rearden
          Mar 7 at 12:25





          If you're using async/await syntax, you are chaining your promises. Maybe that's the bit you're missing? Either way, these sort of questions are a bit easier to answer when they include actual code

          – Daniel Rearden
          Mar 7 at 12:25













          Okey, I will provide code tomorrow and see if I can wrap my head around it easier! Need to see if I can find a template for sharing graphql-backend code easy.

          – user2687506
          Mar 7 at 14:05





          Okey, I will provide code tomorrow and see if I can wrap my head around it easier! Need to see if I can find a template for sharing graphql-backend code easy.

          – user2687506
          Mar 7 at 14:05













          Okay, so I found the issue, and it simply was that I didn't know enough of javascript. It had nothing to do with Apollo-graphql to do at all. I can't really accept that workingRejection2 works where as notWorkingRejection2 doesn't work, but I guess it has to do with me not getting promises 100% yet. codesandbox.io/s/m4q8jy6lvy

          – user2687506
          Mar 7 at 16:43





          Okay, so I found the issue, and it simply was that I didn't know enough of javascript. It had nothing to do with Apollo-graphql to do at all. I can't really accept that workingRejection2 works where as notWorkingRejection2 doesn't work, but I guess it has to do with me not getting promises 100% yet. codesandbox.io/s/m4q8jy6lvy

          – user2687506
          Mar 7 at 16:43



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55025673%2fhow-to-handle-async-errors-correctly%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

          Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

          Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved