Error Handling
This section explains how to manage business logic errors effectively. For example, if you perform a database call to fetch an item by its ID but the item isn't found, you can return an error message as a structured response.
To streamline this process, we introduced a Result
component that simplifies handling success and failure responses.
Result.failure(error)
accepts the error type defined in the.error
method and sends an error response with a status code of 400.- For successful results, use
Result.success(data)
.
This approach ensures consistency and clarity across your application.
Example
index.ts
import { SchemaValidator, endpoint } from "tarin";
// Server initialization
...
// Endpoint definition
const getItemByIdEndpoint = endpoint.get("/api/items/:id")
.input({
params: SchemaValidator.object({
id: SchemaValidator.string(),
}),
})
.output({
body: SchemaValidator.object({
id: SchemaValidator.string(),
title: SchemaValidator.string(),
description: SchemaValidator.string(),
}),
})
.error(SchemaValidator.object({ message: SchemaValidator.string() }))
.handleLogic((input) => {
// Input type: { params: { id: string; } }
// Error type: ({ message: string; }) => void
// Provides autocompletion and type checking in IDEs like VSCode.
const item = getItemById(input.params.id);
if (!item) {
return Result.failure({ message: "Item Not Found" });
}
// Return the expected type:
// { body: { id: string; title: string; description: string; } }
return Result.success({ body: item });
});
tarin.addEndpoints(getItemByIdEndpoint);