Error Handling
Handle HTTP, validation, parsing, abort, and runtime fetch failures.
fetch exposes package-specific errors for expected HTTP and validation failures.
Other platform and schema errors can still propagate from native fetch, body parsing, request construction, or the validator itself.
Package Errors
import { FetchError } from "@zap-studio/fetch/errors";
import { ValidationError } from "@zap-studio/validation/errors";FetchError
FetchError is thrown when a response is not ok and throwOnFetchError is true.
try {
await api.get("/api/users/missing", UserSchema);
} catch (error) {
if (error instanceof FetchError) {
console.error(error.status);
console.error(error.response);
} else {
throw error;
}
}Set throwOnFetchError: false to handle the response manually.
const response = await $fetch("/api/users/missing", {
throwOnFetchError: false,
});
if (!response.ok) {
console.error(response.status);
}ValidationError
ValidationError is thrown when validation returns issues and throwOnValidationError is true.
try {
await api.get("/api/users/1", UserSchema);
} catch (error) {
if (error instanceof ValidationError) {
console.error(error.issues);
} else {
throw error;
}
}Set throwOnValidationError: false to receive the Standard Schema result object.
const result = await api.get("/api/users/1", UserSchema, {
throwOnValidationError: false,
});
if (result.issues) {
console.error(result.issues);
}Other Throwable Errors
Calls can also reject with:
TypeErrorfrom invalid request setup, invalid headers/search params, JSON request serialization, network failures, or response body read failures.DOMExceptionfor aborted requests or aborted response body reads.SyntaxErrorwhen a schema is provided andresponse.json()cannot parse the body.- Any error thrown or rejected by the provided Standard Schema validator.
Exhaustive Handling
Catch package-specific errors first, then rethrow unknown failures.
try {
return await api.get("/api/users/1", UserSchema);
} catch (error) {
if (error instanceof FetchError) {
return { ok: false, reason: "http", status: error.status };
}
if (error instanceof ValidationError) {
return { ok: false, reason: "validation", issues: error.issues };
}
throw error;
}Edit on GitHub
Last updated on