Sub topic 10
Handling errors and partial data
This chapter covers what a graphql wire adapter result looks like when something goes wrong, and how to write components that keep working. It assumes you can already write a query with gql, read edges and node, and pass reactive variables. Those topics come from the earlier chapters.
The shape of a result
The adapter gives your wire function (or wired property) an object with two properties:
data: the GraphQL response data, orundefinedif none is available.errors: an array of error objects, orundefinedif there are no errors.
Both can be present in the same result. Many developers write if (data) { ... } else if (errors) { ... } and assume the two cases are exclusive. That pattern is fine for a first demo, but it silently hides errors whenever the response also contains data.
A result falls into one of four states:
| State | `data` | `errors` | Typical cause |
|---|---|---|---|
| Pending | `undefined` | `undefined` | The request has not finished, or a reactive variable is still `undefined`. |
| Success | present | `undefined` | The query ran and every requested field was returned. |
| Failure | `undefined` | present | The query was rejected, or the request failed before any data came back. |
| Partial | present | present | Some fields or records resolved and others did not. |
Treat these as four separate branches in your component. Pending is not an error, so do not show an error message for it.
Why partial data exists
GraphQL resolves each field independently. If one field cannot be resolved, the server can still return the fields that worked. It sets the failed field to null and adds an entry to the errors array. Each entry normally has a message and may also have path and locations. path points at the field that failed. locations points at the position in the query text.
Two consequences follow:
- A
nullvalue does not by itself mean an error. A field can be legitimately empty. Checkerrorsto tell the difference. - Fields you assumed were non-null may be
nullin a partial result. Code such asnode.Name.valuethrows aTypeErrorifNameisnull.
The exact set of conditions that produce a partial result depends on the server. Do not write code that depends on a specific cause. Write code that handles the shape.
Decision flow for a result
The diagram shows the order in which to check a result.
A component that handles all four states
The component below keeps data and errors in separate properties. Each is updated on every result, so stale values from an earlier result never remain.
import { LightningElement, wire } from 'lwc';
import { gql, graphql } from 'lightning/uiGraphQLApi';
export default class SafeAccountList extends LightningElement {
accounts = [];
errorMessages = [];
hasResult = false;
@wire(graphql, {
query: gql`
query safeAccounts($first: Int) {
uiapi {
query {
Account(first: $first, orderBy: { Name: { order: ASC } }) {
edges {
node {
Id
Name { value }
Industry { value displayValue }
}
}
}
}
}
}
`,
variables: '$variables'
})
wiredAccounts({ data, errors }) {
this.hasResult = Boolean(data || errors);
const edges = data?.uiapi?.query?.Account?.edges ?? [];
this.accounts = edges
.map((edge) => edge?.node)
.filter((node) => node)
.map((node) => ({
id: node.Id,
name: node.Name?.value ?? '(no name)',
industry: node.Industry?.displayValue ?? node.Industry?.value ?? ''
}));
this.errorMessages = (errors ?? []).map((error, index) => ({
key: `error-${index}`,
text: error.message
}));
if (errors) {
// Keep full details for debugging; show only messages to users.
console.error('GraphQL errors', JSON.stringify(errors));
}
}
get variables() {
return { first: 10 };
}
get isPending() {
return !this.hasResult;
}
get hasErrors() {
return this.errorMessages.length > 0;
}
get isEmpty() {
return this.hasResult && !this.hasErrors && this.accounts.length === 0;
}
}Points to notice:
hasResultis set fromdata || errors, so the pending state is only the time before the first result.- Every read uses optional chaining (
?.) and a fallback with??. A partial result can leaveNameorIndustryasnull. - The
.filter((node) => node)step drops edges whosenodeisnull. - The component renders what it has and also reports the errors.
isEmptyis only true when there were no errors. An empty list with errors means "something went wrong", not "no accounts".
The template covers each state:
<template>
<lightning-card title="Accounts" icon-name="standard:account">
<template lwc:if={isPending}>
<lightning-spinner alternative-text="Loading accounts" size="small"></lightning-spinner>
</template>
<template lwc:if={hasErrors}>
<div class="slds-p-around_medium slds-text-color_error" role="alert">
<p>Some account data could not be loaded.</p>
<ul>
<template for:each={errorMessages} for:item="error">
<li key={error.key}>{error.text}</li>
</template>
</ul>
</div>
</template>
<template lwc:if={isEmpty}>
<p class="slds-p-around_medium">No accounts found.</p>
</template>
<ul class="slds-p-around_medium">
<template for:each={accounts} for:item="account">
<li key={account.id}>{account.name} {account.industry}</li>
</template>
</ul>
</lightning-card>
</template>The error block and the list are separate on purpose. In a partial result both appear: the records that loaded, and a notice that something is missing.
Which messages to show users
The message text comes from the server and is written for developers. It may name fields or objects. Decide per component how much to expose:
- For end users, show one fixed sentence, such as "Some account data could not be loaded."
- For admins or developer tools, show the messages.
- Always log the full error array (as in the example) so the failure can be diagnosed from the browser console.
Do not parse message strings to decide what to do. The wording can change between releases. If you need to branch on a cause, prefer structured properties such as path when they are present.
Common mistakes
- Checking
errorsonly whendatais missing. This hides partial failures. Check both independently. - Reading
node.Field.valuewithout guarding. Anullfield wrapper throws and breaks the whole render. Use?.and a default. - Treating an empty list as success. If
errorsis present, an empty list can mean the query failed. Show the error state first. - Showing an error during the pending state. Before the first result, both
dataanderrorsareundefined. A reactive variable that isundefinedproduces the same state, because the wire does not run until it has a value. - Leaving stale state. If you only assign
this.accountswhendataexists, a later failing result leaves the old records on screen. Assign on every result, as in the example. - Mutating the result. Wire results are read-only. Copy the values you need into new objects, as the example does with
map.
Testing the error paths
You can test these branches without a failing server. The Jest test utilities for the wire adapter let you emit a result object, so you can emit one with errors only, one with data and errors, and one with neither. Check that the component renders the right branch each time. A partial result with a null field wrapper is the most valuable case, because it is the one that breaks code written for the success path only.
What comes next
Errors are one reason a result can look incomplete. The next chapter covers refreshing: re-running a query after data changes, so that a fixed problem or a new record shows up without reloading the page. A later chapter covers sharing rules, field-level security, and query limits, which are common causes of the errors discussed here.
Exercise
A wire function contains if (data) { this.accounts = ...; } else if (errors) { this.errors = errors; }. The server returns data for 8 accounts plus one error entry for a failed field. What does the user see, and how would you fix the code?
Show answer
The user sees the 8 accounts and no error, because the else if branch never runs when data is present. The failure is hidden. Fix it by checking data and errors in two separate statements, so this.errors is set whenever errors is present. Assign both properties on every result, and use optional chaining when reading fields, because the failed field is null.
Exercise
Why is "no accounts found" the wrong message when accounts.length === 0 and errors is defined?
Show answer
An empty list together with errors can mean the query failed, not that no records exist. Show the error state instead, and only show "no accounts found" when the result has no errors.