{"id":8185,"date":"2024-09-03T22:33:50","date_gmt":"2024-09-03T17:03:50","guid":{"rendered":"https:\/\/pheonixsolutions.com\/blog\/?p=8185"},"modified":"2024-09-03T22:33:54","modified_gmt":"2024-09-03T17:03:54","slug":"error-handling-in-graphql-with-apollo-server","status":"publish","type":"post","link":"https:\/\/pheonixsolutions.com\/blog\/error-handling-in-graphql-with-apollo-server\/","title":{"rendered":"Error Handling in GraphQL with Apollo Server"},"content":{"rendered":"\n<p class=\"has-text-align-left wp-block-paragraph\">Apollo Server is a tool that helps to create GraphQL APIs easily. It makes setting up a GraphQL server simple and fast, allowing to define how data is organized and accessed. Apollo server also has built-n support for handling errors and monitoring performance.<\/p>\n\n\n\n<p class=\"has-text-align-left wp-block-paragraph\">Error handling in GraphQL with Apollo Server helps users clearly understand any issues. When errors are handled correctly, users get clear messages about what went wrong and what they should do next. This makes the API more reliable and provides a better experience for everyone.<\/p>\n\n\n\n<p class=\"has-text-align-left wp-block-paragraph\"><strong>default status codes<\/strong>: <br>Apollo Server is responds with two status codes, which is basically:<br> 200 : This Status code returned even if errors occur during execution<br> 500 : This status code indicates  internal server error.<br><br><strong>Install apollo server express:<\/strong><br>yarn add apollo-server-express <br><br><strong><em>Example:<\/em><\/strong><br>import { ApolloError, UserInputError } from &#8220;apollo-server-express&#8221;;<br>import { Types } from &#8220;mongoose&#8221;;<br><br>getBorrowerbyID<strong>:<\/strong> async (_: any, { id }: { id: string }) =&gt; {<br> if (!Types.ObjectId.isValid(id)) {<br> throw new UserInputError(BORROWER.INVALID_ID);<br>\u00a0 }<br>\u00a0try {<br>const borrower = await BorrowerModel.findById(id);<br>\u00a0 \u00a0 \u00a0 \u00a0 if (!borrower) {<br>         throw new ApolloError(BORROWER.BORROWERNOTFOUND);<br>\u00a0         }<br>return borrower;<br>} catch (error) {<br>\u00a0 throw new ApolloError(BORROWER.INTERNAL_SERVER_ERROR);<br> }<br>},<br><br><strong>Basic Error handling: <\/strong><br>Using ApolloError to return general errors and Handle unexpected issues.<br><br><strong>User Input Error:<\/strong><br> It validate the user input and if its not validate returns specific error.<br> if (!Types.ObjectId.isValid(id)) {<br> throw new UserInputError(BORROWER.INVALID_ID);<br>\u00a0 }<br><strong>Format Error: <\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">By default Apollo server Provides a basic error format. To customize the below error format globally, we can use<strong><em> formatError<\/em><\/strong> function.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><a href=\"https:\/\/pheonixsolutions.com\/blog\/wp-content\/uploads\/2024\/09\/image.png\"><img fetchpriority=\"high\" decoding=\"async\" width=\"762\" height=\"487\" src=\"https:\/\/pheonixsolutions.com\/blog\/wp-content\/uploads\/2024\/09\/image.png\" alt=\"\" class=\"wp-image-8193\" srcset=\"https:\/\/pheonixsolutions.com\/blog\/wp-content\/uploads\/2024\/09\/image.png 762w, https:\/\/pheonixsolutions.com\/blog\/wp-content\/uploads\/2024\/09\/image-300x192.png 300w, https:\/\/pheonixsolutions.com\/blog\/wp-content\/uploads\/2024\/09\/image-469x300.png 469w\" sizes=\"(max-width: 762px) 100vw, 762px\" \/><\/a><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\"><br>To Add this formatError function inside index.ts file :<br>import { GraphQLError, GraphQLFormattedError } from &#8216;graphql&#8217;;<br>const formatError = (error: GraphQLError): GraphQLFormattedError =&gt; {<br>const { message } = error;<br>return { message };<br>};<br>const server = new ApolloServer({<br>  typeDefs,<br>  resolvers,<br>  context,<br>  formatError,<br>});<br>After implementing<em> formatError<\/em> function, error response will include error details inside message field.<br><br><strong>Conclusion:<\/strong><br>Using ApolloError and UserInputError provides clear error messages, making it easier to understand issues. <\/p>\n","protected":false},"excerpt":{"rendered":"<p>Apollo Server is a tool that helps to create GraphQL APIs easily. It makes setting up a GraphQL server simple [&hellip;]<\/p>\n","protected":false},"author":501,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_feature_clip_id":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_publicize_message":"","jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":false,"jetpack_social_options":{"image_generator_settings":{"template":"highway","default_image_id":0,"font":"","enabled":false},"version":2},"jetpack_post_was_ever_published":false},"categories":[1022],"tags":[],"class_list":["post-8185","post","type-post","status-publish","format-standard","hentry","category-web-architecture","psol-cat-web-architecture"],"jetpack_publicize_connections":[],"jetpack_shortlink":"https:\/\/wp.me\/phn2x7-281","jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/8185","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/users\/501"}],"replies":[{"embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/comments?post=8185"}],"version-history":[{"count":0,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/posts\/8185\/revisions"}],"wp:attachment":[{"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/media?parent=8185"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/categories?post=8185"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pheonixsolutions.com\/blog\/wp-json\/wp\/v2\/tags?post=8185"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}