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?
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
add a comment |
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
add a comment |
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
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
javascript node.js graphql apollo-server
asked Mar 6 at 14:39
user2687506user2687506
419213
419213
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
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()
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 thatworkingRejection2
works where asnotWorkingRejection2
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
add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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()
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 thatworkingRejection2
works where asnotWorkingRejection2
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
add a comment |
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()
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 thatworkingRejection2
works where asnotWorkingRejection2
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
add a comment |
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()
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()
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 thatworkingRejection2
works where asnotWorkingRejection2
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
add a comment |
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 thatworkingRejection2
works where asnotWorkingRejection2
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
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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