Quoting the docs on Type Safe Error Handling:
Type safe error handling
A. When an error is gracefully provided from a base query, RTK query will provide the error directly.
B. If an unexpected error is thrown by user code rather than a handled error, that error will be transformed into a SerializedError
shape.
Users should make sure that they are checking which kind of error they are dealing with before attempting to access its properties. This can be done in a type safe manner either by using a type guard, e.g. by checking for discriminated properties, or using a type predicate.
When using fetchBaseQuery
, as your base query, errors will be of type FetchBaseQueryError | SerializedError
.
When using fetchBaseQuery
, the error property returned from a hook will have the type FetchBaseQueryError | SerializedError | undefined
. If an error is present, you can access error properties after narrowing the type to either FetchBaseQueryError
or SerializedError
.
Example:
import { api } from './services/api'
function PostDetail() {
const { data, error, isLoading } = usePostsQuery()
if (isLoading) {
return <div>Loading...</div>
}
// Possible values of error:
// FetchBaseQueryError | SerializedError | undefined
// 1) Checking if error is NOT undefined:
if (error) {
// 2) Checking if error is FetchBaseQueryError based on
// discriminated property 'status':
if ('status' in error) {
// you can access all properties of `FetchBaseQueryError` here
const errMsg = 'error' in error ? error.error : JSON.stringify(error.data)
return (
<div>
<div>An error has occurred:</div>
<div>{errMsg}</div>
</div>
)
// 3) We're left with the 3rd case, SerializedError:
} else {
// you can access all properties of `SerializedError` here
return <div>{error.message}</div>
}
}
{error && <div>Error: {error.message}</div>}
– ChlorobenzeneProperty 'message' does not exist on type 'FetchBaseQueryError | SerializedError'. Property 'message' does not exist on type '{ status: number; data: unknown; }'.
– Brokenhearted{error && ( <div> Error: {error instanceof FetchBaseQueryError ? error.status : error.message} </div> )}
– Chlorobenzene