Effect CommunityEC
Effect Community4w ago
2 replies
amanuel

Using Effect for Error Handling in TypeScript API

hey ya'll, I have a bunch of service/controllers like this:

// service
export async function updateEventType(
    eventTypeId: string,
    userId: string,
    update: EventTypeUpdate,
) {
    const now = Temporal.Now.instant().toString();

    const result = await dbQuery(
        db
            .update(eventType)
            .set({ ...update, updatedAt: now })
            .where(and(eq(eventType.id, eventTypeId), eq(eventType.userId, userId)))
            .returning({ id: eventType.id }),
    );

    if (!result.ok) {
        return result;
    }

    if (result.value.length === 0) {
        return Result.err(new NotFoundError());
    }

    return Result.ok();
}

// controller
async ({ user, params: { id }, body, status }) => {
    const result = await updateEventType(id, user.id, body);

    if (!result.ok) {
        if (result.error instanceof NotFoundError) {
            return status(404, result.error.toApiError());
        }
        return status(500, result.error.toApiError());
    }
}



I want to try to convert just this aspect of my API to use Effect's error handling without turning everything into effect. I just want to be able to wrap my db calls and also throw my own Errors that I can catch and handle before returning a response. I would appreciate any help with getting started, would love to compare the dx boost versus a simple implementation that I have made myself, at least for simple endpoints like this it is working very well, but want to see if I'm missing something.
Was this page helpful?