Nunca Lanca Excecoes
Todos os erros sao retornados como valores, nao excecoes. Sem mais blocos try-catch ou lancamentos inesperados.
Inspirado no padrao de tratamento de erros do Go, construido sobre a API Fetch nativa
import { typedFetch, NotFoundError, UnauthorizedError, isHttpError, isNetworkError } from '@pbpeterson/typed-fetch';
interface User {
id: number;
name: string;
email: string;
}
type ExpectedErrors = NotFoundError | UnauthorizedError;
const { response, error } = await typedFetch<User[], ExpectedErrors>('/api/users');
if (error) {
if (error instanceof NotFoundError) {
console.log('Users not found');
} else if (error instanceof UnauthorizedError) {
console.log('Authentication required');
} else if (isNetworkError(error)) {
console.log('Network error:', error.message);
} else {
// Server errors (5xx) are always included
console.log(`HTTP ${error.status}: ${error.statusText}`);
}
} else {
const users = await response.json(); // Type: User[]
console.log('Users:', users);
}Bibliotecas fetch tradicionais lancam excecoes em erros HTTP, tornando o tratamento de erros complicado e propenso a falhas. typed-fetch segue a filosofia do Go de tratamento de erros explicito - erros sao valores, nao excecoes.
try {
const response = await fetch('/api/users');
const users = await response.json(); // E se a resposta for 404?
} catch (error) {
// Lidar com erros de rede, erros de parsing, erros HTTP... tudo misturado
}import { typedFetch, NotFoundError, isHttpError } from '@pbpeterson/typed-fetch';
type ExpectedErrors = NotFoundError;
const { response, error } = await typedFetch<User[], ExpectedErrors>('/api/users');
if (error) {
if (error instanceof NotFoundError) {
const details = await error.json<{ message: string }>();
console.log(details.message); // typed!
}
} else {
const users = await response.json(); // Type: User[]
}npm install @pbpeterson/typed-fetchpnpm add @pbpeterson/typed-fetchyarn add @pbpeterson/typed-fetchConfira o guia Primeiros Passos para aprender a usar typed-fetch no seu projeto.