APIs & Services
...
Getting Started
Error Handling

Union Errors

8min

Introduction to Union Types in GraphQL GraphQL's union types allow fields to return one of several different types of error responses. This is particularly useful when a query might return a successful result or various types of errors, such as validation or generic errors.

Key Components of the Union Type Implementation

  1. Success Type: Represents the normal, successful response. Example: Organization type containing the organization details.
  2. Error Types: ValidationError: Includes details about validation issues, such as missing or invalid fields. GenericError: Handles any generic errors that don’t fall under validation, such as internal server issues.



Usage Examples in Client-Side Applications To handle union types in client-side applications, you can leverage the __typename field, which helps identify the exact type of the response.

Handling Success and Error on the Client:

const query = gql query GetOrganization($id : ID !) { getOrganization(id : $id) {...on Organization { id name website }...on ValidationError { message field }...on GenericError { message errorCode } } };
apolloClient.query({ query, variables: { id: "1" } }) .then(response => { const result = response.data.getOrganization; if (result.__typename === 'Organization') { console.log('Organization details:', result); } else if (result.__typename === 'ValidationError') { console.log('Validation Error:', result.message); } else if (result.__typename === 'GenericError') { console.log('Generic Error:', result.message); } });



The migration to union types in your GraphQL responses significantly enhances the API’s usability, clarity, and error management. By leveraging this approach, you can provide a more robust and predictable contract to API consumers, ensuring that both successful and error states are handled consistently.

Error Structure

Generic Error

... on GenericError { __typename correlationId errorCode errorMessage }

Validation Error

... on ValidationError { __typename errorMessage errorCode correlationId errorDetails { code message path } }

Generic Errors

  • When an API request fails, the API Gateway can return a GenericError to provide essential information about the failure. This type of error is used for system-level issues such as server malfunctions, internal failures, or when the request cannot be processed due to infrastructure-related problems.
  • The GenericError is designed to give the client a basic but meaningful description of the error, so they can identify the problem and take appropriate action..
  • When the Generic Error filter is configured, the API Gateway examines the incoming message and attempts to infer the type of message to be returned.
  • Query body’s information
    • typename - Indicates the type of error, which in this case will be GenericError. It helps clients distinguish between different error types, such as GenericError vs. ValidationError.
    • errorMessage - A brief description of the issue that occurred. This message helps explain the error, though it may not provide specific technical details..
    • errorCode - displays the error code.
    • correlationId - An id used to correlate logs and metrics across services and processes.
  • For example lets hit this query in Profile API , For an incoming JSON message, the API Gateway sends an appropriate JSON response

Request

query MyQuery { organizationBulkIDSearch(filter: {ids: ""}) { ... on OrganizationPagedResult { __typename items { id } } ... on GenericError { __typename correlationId errorMessage errorCode } ... on ValidationError { __typename correlationId errorCode errorMessage errorDetails { code path message } } } }

Response

{ "data": { "organizationBulkIDSearch": { "__typename": "GenericError", "correlationId": "", "errorMessage": "search_phase_execution_exception: [query_shard_exception] Reason: failed to create query: Ids can't be empty", "errorCode": "500" } } }

Validation Error

  • Validation Error occurs when a request is malformed or the request failed our validation rules.
  • It occurs when the required parameters are missing (either in body or in query string).
  • Query body’s information
    • typename - It shows the type of error that has occurred, either generic or validation.
    • errorMessage - elaborates the requirement for the input values.
    • errorCode - displays the error code.
    • correlationId - an id used to correlate logs and metrics across services and processes -
    • errorDetails - Displays the detailed information about the error.
  • For Example For example lets hit this query in Profile API.

Request

query personKeywordSearch_Inline_Fragments { personKeywordSearch (filter:{searchKeyword:""}, pageInfo: {first:30} ) { ... on PersonPagedResult { __typename items { __typename name id firstName middleName lastName } pageInfoResponse { totalCount pageInfo { startCursor endCursor hasNextPage } } } ... on GenericError { __typename correlationId errorCode errorMessage } ... on ValidationError { __typename errorMessage errorCode correlationId errorDetails { code message path } } } }

Response

{ "data": { "personKeywordSearch": { "__typename": "ValidationError", "errorMessage": "Minimum two characters needed to perform keyword search", "errorCode": "400", "correlationId": "", "errorDetails": null } } }

Important Note

All GraphQL queries must be embedded with the below query

.. on GenericError { __typename correlationId errorCode errorMessage } ... on ValidationError { __typename errorMessage errorCode correlationId errorDetails { code message path } }



Updated 09 Oct 2024
Doc contributor
Doc contributor
Did this page help you?