`catcherFallback()` / `catcher()` error type is too narrow / `customError` naming suggestion
Description
Two related issues with error handling types:
-
customError()naming: This method only intercepts response errors (HTTP errors with a response). Request-level errors (network failures, CORS, etc.) bypass it entirely. The namecustomResponseErrorwould better communicate this behavior. -
catcherFallback()andcatcher()receive wrong type: The error parameter is typed as the return type ofcustomError(), but they can also receive request-level errors that never pass throughcustomError().
Reproduction
import wretch from "wretch";
class ApiError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}
const api = wretch()
.customError(async (error) => {
// This only runs for HTTP response errors
return new ApiError(error.status, error.message);
})
.catcher(404, (error) => {
// TypeScript thinks `error` is `ApiError`
// But request-level errors can also end up here
console.log(error);
})
.catcherFallback((error) => {
// TypeScript thinks `error` is `ApiError`
// But if you block the URL in Chrome DevTools (or network is down):
// `error` is actually `TypeError: Failed to fetch`
console.log(error); // TypeError, not ApiError!
});
Cause
catcher() and catcherFallback() are typed to receive the custom error type (ApiError in the example above), but request-level errors like TypeError: Failed to fetch bypass customError() entirely and arrive at these handlers as their original type.
Suggested Fix
- Consider renaming
customError→customResponseErrorto clarify it only handles response errors - Change
catcher()andcatcherFallback()error parameter type tounknownto reflect that they may receive either custom response errors or raw request errors
Environment
- wretch: 3.0.5