Skip to content

Commit 58273bf

Browse files
feat: add tryCatch utility function and update tests
1 parent 916255e commit 58273bf

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"name": "@primoui/utils",
33
"description": "A lightweight set of utilities",
4-
"version": "1.1.9",
4+
"version": "1.1.10",
55
"license": "MIT",
66
"type": "module",
77
"author": {

src/helpers/helpers.test.ts

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
slugify,
1313
splitArrayChunks,
1414
stripHtml,
15+
tryCatch,
1516
} from "./helpers"
1617

1718
describe("range", () => {
@@ -173,3 +174,22 @@ describe("joinAsSentence", () => {
173174
expect(joinAsSentence(["apple", "banana", "cherry"], 2)).toEqual("apple and banana")
174175
})
175176
})
177+
178+
describe("tryCatch", () => {
179+
it("should return data when promise resolves", async () => {
180+
const promise = Promise.resolve("success")
181+
const result = await tryCatch(promise)
182+
183+
expect(result.data).toEqual("success")
184+
expect(result.error).toBeNull()
185+
})
186+
187+
it("should return error when promise rejects", async () => {
188+
const error = new Error("failure")
189+
const promise = Promise.reject(error)
190+
const result = await tryCatch(promise)
191+
192+
expect(result.data).toBeNull()
193+
expect(result.error).toEqual(error)
194+
})
195+
})

src/helpers/helpers.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,3 +197,38 @@ export const joinAsSentence = (items: string[], maxItems = 3, lastItem = "and")
197197
.join(", ")
198198
.replace(/, ([^,]*)$/, ` ${lastItem} $1`)
199199
}
200+
201+
/**
202+
* A type representing a successful result with data and no error.
203+
*/
204+
type Success<T> = {
205+
data: T
206+
error: null
207+
}
208+
209+
/**
210+
* A type representing a failed result with no data and an error.
211+
*/
212+
type Failure<E> = {
213+
data: null
214+
error: E
215+
}
216+
217+
/**
218+
* A type representing a result with either data or an error.
219+
*/
220+
type Result<T, E = Error> = Success<T> | Failure<E>
221+
222+
/**
223+
* Wraps a promise and returns a result object with the data or error
224+
* @param promise - The promise to wrap
225+
* @returns A result object with the data or error
226+
*/
227+
export const tryCatch = async <T, E = Error>(promise: Promise<T>): Promise<Result<T, E>> => {
228+
try {
229+
const data = await promise
230+
return { data, error: null }
231+
} catch (error) {
232+
return { data: null, error: error as E }
233+
}
234+
}

0 commit comments

Comments
 (0)