Client
Error Handling

Error Handling

When interacting with APIs, error handling is a crucial aspect. In feTS Client, we return a WHATWG Response object for every request. This allows you to either use the status attribute to handle specific status codes or the ok attribute to verify whether the response was successful.

Let’s explore how you can manage various scenarios.

Handling Common HTTP Errors

Suppose you have an endpoint /pet/{id} that fetches a pet object. If no pet matches the given id, the server will return a 404 status code. Here’s how you can handle this:

const response = await client['/pet/{id}']({
    params: {
        id: 1
    }
 });
 
if (response.status === 404) {
    console.error('Pet not found');
    return;
}
 
// Or handle errors
if (!response.ok) {
    console.error('Something went wrong');
    const errorResponse = await response.text();
    console.log(errorResponse);
    return;
}
 
const pet = await response.json();
console.log(`Pet name is ${pet.name}`);

Working with Validation Errors in feTS Server

When using feTS Server, request validation errors are thrown as ClientValidationError. You can handle them as shown below:

import { ClientValidationError } from 'fets';
 
try {
    const response = await client['/pet/:id']({
        params: {
            id: 1
        }
    });
 
    if (response.status === 404) {
        console.error('Pet not found');
        return;
    }
 
    const pet = await response.json();
    console.log(`Pet name is ${pet.name}`);
} catch (error) {
    if (error instanceof ClientValidationError) {
        console.error('Validation error', error.errors);
    }
}