Guide
Observability
Typed errors, structured logging, and error reporting hooks
Errors
Every failure from Fileway is a StorageError (exported from @fileway/core) carrying a stable, machine-readable code you can branch on: check err.code, not err.message or instanceof (which doesn't survive across realms like workers/iframes):
import { StorageError } from "@fileway/core";
try {
await client.upload(stream, { filename: "a.png" });
} catch (err) {
if (err instanceof StorageError) {
switch (err.code) {
case "auth-failed": // bad/expired credentials
case "bucket-not-found":
case "size-exceeded":
case "rate-limited": // the provider is throttling; safe to retry
case "timeout": // an attempt stalled (retry.idleTimeoutMs); safe to retry
case "network": // fetch-level failure; safe to retry
case "provider-error": // 5xx etc.; safe to retry
}
}
}The StorageErrorCode union
| Code | Meaning | Retry? |
|---|---|---|
validation | Malformed input (ValidationError: invalid filename, size, expiresIn, escaping path, etc.) | Never; fix the call |
config | Driver misconfiguration (e.g. missing S3 credentials, driver lacks presigned-URL support) | Never; fix the config |
not-found | The object/asset does not exist | No |
bucket-not-found | The S3 bucket / Cloudinary cloud does not exist or is not reachable | No |
auth-failed | Invalid or expired credentials, access denied | Re-auth, then retry |
size-exceeded | Payload over the provider limit (EntityTooLarge, 413) | No |
conflict | The destination of a copy or move already exists and overwrite is not set | No; pick another path or pass overwrite: true |
rate-limited | The provider is throttling: HTTP 429, or its own code (S3 SlowDown, Azure ServerBusy, Cloudinary 420) | Yes, with backoff |
timeout | An attempt made no progress within retry.idleTimeoutMs | Yes, with backoff |
network | fetch failed before an HTTP response (DNS, socket, TLS) | Yes, with backoff |
provider-error | The provider returned an HTTP error without a more specific classification (e.g. 5xx) | Yes, with backoff |
StorageError also exposes:
statusCode: the HTTP status when the failure came from an HTTP response (404, 403, 500, …).provider: which driver produced it:"s3","cloudinary", or"local".cause: the wrapped underlying error when one exists (e.g. the originalTypeError("fetch failed")fornetworkerrors).toJSON(): serializes to{ name, code, message, statusCode?, provider? }for logs.isAbortError(err):truewhenerris the standardDOMException/AbortErrorproduced by upload cancellation (a cancellation is not aStorageError).
How codes are derived per driver
| Driver | Classification |
|---|---|
LocalDriver | Missing file → not-found; escaping path → validation. |
S3Driver | Parses the AWS/MinIO XML <Code> (NoSuchBucket, NoSuchKey/NoSuchUpload, AccessDenied/InvalidAccessKeyId/SignatureDoesNotMatch/ExpiredToken/InvalidToken, EntityTooLarge) with an HTTP-status fallback (401/403 → auth-failed, 404 → not-found, 413 → size-exceeded, else provider-error). fetch failures → network; missing credentials → config. |
GCSDriver | JSON error body and HTTP status: 401/403 → auth-failed, 404 → not-found or bucket-not-found (from the message), 413 → size-exceeded; a rejected token exchange → auth-failed. |
AzureDriver | The x-ms-error-code header (ContainerNotFound, BlobNotFound, AuthenticationFailed/AuthorizationFailure, RequestBodyTooLarge), with an HTTP-status fallback. |
SupabaseDriver | The JSON body first (Storage often answers 400 with the real status inside): bucket or object not found, JWT and RLS failures → auth-failed, size limits → size-exceeded. |
CloudinaryDriver | HTTP status mapping: 401/403 → auth-failed, upload 404 → bucket-not-found, get 404 → not-found, 413 → size-exceeded, else provider-error. fetch failures → network. |
Abort signals are never wrapped: cancelling an upload rejects with a plain DOMException named AbortError (see Cancelling uploads), which isAbortError() recognizes. This is the same error fetch itself throws on abort, so your cancellation handling works uniformly.
Events
For a structured record of every operation (success or failure, with timing, retries and who did it), use a plugin's onEvent. It suits audit trails, usage metering and dashboards better than log lines. See Plugins and Events.
Retries
Fileway retries transient failures automatically at the client layer: no driver changes, no manual loops. What is worth retrying:
- Retryable:
network,timeout,rate-limited,provider-error, or any error carrying HTTP429/5xx. - Never retried:
validation,config,auth-failed,not-found,bucket-not-found,size-exceeded, andAbortError.
const client = new FilewayClient({
driver,
retry: {
maxRetries: 3, // attempts after the first (default 3, 0 disables)
baseDelayMs: 300, // first delay (default 300)
maxDelayMs: 10_000, // cap on any delay (default 10_000)
multiplier: 2, // exponential backoff (default 2)
jitter: true, // full jitter to avoid thundering herd (default true)
// retryHttpStatuses: [408], // opt-in extra statuses
// retryGenericErrors: true, // retry all non-StorageError failures (default: only TypeError)
// idleTimeoutMs: 30_000, // retry an attempt that makes no progress for 30 s (default: off)
},
});Which operations retry
delete,get,getUrl,getPresignedUrlretry automatically (they're idempotent).uploadretries only when you passstreamFactory. AReadableStreamis consumed after one read, so without a way to re-produce the payload a failed upload can't be retried. ProvidestreamFactoryto create a fresh stream per attempt; the source must be re-readable (a file path, in-memory bytes, a re-fetchable URL):
const result = await client.upload(createReadStream(file), {
filename: "photo.jpg",
size: stat.size,
streamFactory: () => createReadStream(file), // fresh stream per retry
});If streamFactory is absent, a failed upload throws immediately (no retry). Because each retry re-transmits the payload, retried uploads cost N+1 egresss on N failures.
Backoff & logging
Retries use exponential backoff with full jitter, capped at maxDelayMs; the wait is interruptible by an abort signal (options.signal on upload, { signal } on delete/get/getUrl/getPresignedUrl). Each retry emits a warn-level log ("<operation> failed, retrying" with { attempt, maxRetries, delayMs, error }), and onError fires only on the final failure, not per attempt.
Timing out stuck attempts
A retry only happens after an attempt fails. A connection that stays open while the provider never answers would otherwise wait forever, so set idleTimeoutMs to cancel an attempt that stops making progress and retry it:
const client = new FilewayClient({
driver,
retry: { idleTimeoutMs: 30_000 },
});- Uploads: the timer measures inactivity, not total time, so large uploads on slow links are fine as long as data keeps moving. It resets every time the driver reads from your stream, and once the stream is fully read it limits the wait for the provider's reply.
- Other operations:
delete,get,getUrl,getPresignedUrlandgetUploadStatusget a plain time limit per attempt, and the timed-out request is cancelled. Forgetit ends when the response starts, not after you read the body. - What a timeout looks like: a
StorageErrorwith codetimeout("upload attempt timed out after 30000 ms without progress"), retried like a network failure. If the provider stored the file anyway, the lost-response check returns it instead of re-sending. - Your own
signalstays final. Cancelling withoptions.signalends the upload; it is never retried.
Choosing a value:
- Parts and chunks pause reading. S3 multipart uploads (8 MiB parts by default) and Cloudinary chunked uploads (20 MiB chunks) stop reading your stream while a part is in flight. Set
idleTimeoutMsabove the time one part takes on your slowest link (8 MiB at 2 Mbit/s is about 34 s). - A slow source looks the same as a slow network. If you relay an upload from a user's browser, a pause on their side also counts as no progress, and a retry needs
streamFactoryto replay it. Use a generous value there, or leave the option off. - Retries re-send the payload, so each timeout that leads to a retry costs another upload's worth of egress.
Note on breaking changes
ValidationError is now a StorageError subclass, and driver messages are unchanged, so existing try/catch, err.message, and instanceof ValidationError checks keep working. Adding the code field is additive.
Logging & Error Reporting
Attach your own loggers and error reporters as FilewayClient config: no SDK, no dependencies, no adapter package. Fileway only defines a minimal contract; you adapt your tooling with a few lines.
logger
Pass any object implementing { debug?, info?, warn?, error? } (all methods optional):
const client = new FilewayClient({
driver,
logger: {
info: (message, meta) => console.log(`[fileway] ${message}`, meta),
error: (message, meta) => console.error(`[fileway] ${message}`, meta),
},
});Fileway calls info with "upload started" / "upload succeeded" (and the equivalents for delete, get, getUrl, getPresignedUrl) plus structured meta ({ operation, path, filename, size, id, url, durationMs }), and error on every failure. Nothing is logged when logger is omitted. A throwing logger is caught and never breaks the operation it is reporting on.
Pino: its (obj, msg) signature is nearly compatible; adapt with a tiny wrapper:
import pino from "pino";
const pinoLogger = pino();
const client = new FilewayClient({
driver,
logger: {
info: (message, meta) => pinoLogger.info(meta ?? {}, message),
warn: (message, meta) => pinoLogger.warn(meta ?? {}, message),
error: (message, meta) => pinoLogger.error(meta ?? {}, message),
},
});Datadog / any async logger: the contract methods are void, so adapt async senders by queueing or fire-and-forget (Fileway does not await logger methods):
logger: {
info: (message, meta) => { void sendToDatadog("info", message, meta); },
error: (message, meta) => { void sendToDatadog("error", message, meta); },
}onError
Called (and awaited) when an operation throws (before the error is re-thrown to your caller) with the raw error and a { operation, durationMs, filename?, path?, mimeType?, size? } context. Use it to report typed failures to Sentry or your own tracker:
import * as Sentry from "@sentry/nextjs";
const client = new FilewayClient({
driver,
onError: (error, context) => {
if (error instanceof StorageError) {
Sentry.captureException(error, {
tags: {
fileway: "1",
operation: context.operation,
provider: error.provider ?? "unknown",
code: error.code,
},
extra: { statusCode: error.statusCode, path: context.path },
});
}
},
});Rules:
- Aborts are not errors. Cancelling an upload (
AbortError) never firesonError. ValidationErrorandconfigerrors do fire: they're client bugs worth seeing.- A throwing
onErroris swallowed: it never masks the original error. - The error is re-thrown to your code after
onErrorcompletes, so your existing error handling is unchanged.
Choosing between them
Use logger | Use onError |
|---|---|
| Structured success/start events ("upload succeeded", duration) | Failures only |
| Local/file logging, Pino pipelines | Sentry/Datadog error tracking |
| Fire-and-forget (not awaited) | Awaited before rethrow (can flush) |
Both can be set together: logger for the audit trail, onError for alerting.
Was this page helpful?