Skip to content

Advanced Usage

Error Response Bodies

typescript
import { typedFetch, BadRequestError } from '@pbpeterson/typed-fetch';

// POST requests commonly expect BadRequestError for validation failures
const { response, error } = await typedFetch<User, BadRequestError>('/api/users', {
  method: 'POST',
  body: JSON.stringify(invalidData)
});

if (error) {
  if (error instanceof BadRequestError) {
    const validationErrors = await error.json();
    console.log('Validation error details:', validationErrors);
  } else {
    // Server errors or network errors
    const errorBody = await error.json();
    console.log('Server error details:', errorBody);
  }
  
  const contentType = error.headers.get('content-type');
  console.log(`Error ${error.status}: ${error.statusText}`);
}

Network vs HTTP Errors

typescript
import { typedFetch, NetworkError, NotFoundError, UnauthorizedError } from '@pbpeterson/typed-fetch';

// Specify expected errors for better type safety
type ExpectedErrors = NotFoundError | UnauthorizedError;
const { response, error } = await typedFetch<User, ExpectedErrors>('/api/users');

if (error) {
  if (error instanceof NetworkError) {
    console.log('Network issue - check connection');
  } else if (error instanceof NotFoundError) {
    console.log('User not found');
  } else if (error instanceof UnauthorizedError) {
    console.log('Authentication required');
  } else {
    // Server errors (5xx)
    console.log(`Server error: ${error.status}`);
  }
}

Optional RequestInit

The second parameter is optional, but you should still specify expected errors.

typescript
import { typedFetch, NotFoundError, UnauthorizedError } from '@pbpeterson/typed-fetch';

// Even with minimal usage, specify expected errors for better type safety
type ExpectedErrors = NotFoundError | UnauthorizedError;
await typedFetch<User[], ExpectedErrors>('/api/users');

Released under the MIT License.