Skip to content

Commit

Permalink
🐛 Fix(package): add missing TSDocs, change enum StatusCode to object …
Browse files Browse the repository at this point in the history
…and add type StatusCode"
  • Loading branch information
INeedJobToStartWork committed Nov 9, 2024
1 parent 12098d8 commit 4c9780c
Show file tree
Hide file tree
Showing 13 changed files with 267 additions and 91 deletions.
8 changes: 8 additions & 0 deletions .changeset/pre.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"mode": "pre",
"tag": "prerelease.2",
"initialVersions": {
"oh-my-error": "2.0.0-prerelease.1"
},
"changesets": ["short-eels-sparkle"]
}
7 changes: 7 additions & 0 deletions .changeset/short-eels-sparkle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"oh-my-error": major
---

- Add type `StatusCode`
- Add missing TSDocs
- Change enum StatusCode to object
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@
dist/*
lib/*
pnpm-lock.yaml

*.md
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# oh-my-error

## 2.0.0-prerelease.2

### Patch Changes

- Add type `StatusCode`
- Add missing TSDocs
- Change enum StatusCode to object

## 2.0.0-prerelease.1

### Minor Changes
Expand Down
33 changes: 17 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,19 +47,19 @@ const data = myErrorWrapper(readFile, Error("Cant Load File!"))("...path");
# 📜 List of Contest

- [📜 List of Contest](#-list-of-contest)
- [Install](#install)
- [TLDR (Only Most Important!)](#tldr-only-most-important)
- [Functions](#functions)
- [Types](#types)
- [Functions](#functions-1)
- [myError `♻️ Refactored`](#myerror-️-refactored)
- [myErrorWrapper `🎉 New feature!`](#myerrorwrapper--new-feature)
- [myErrorCatcher](#myerrorcatcher)
- [myErrorHandler](#myerrorhandler)
- [Types](#types-1)
- [TMyErrorList](#tmyerrorlist)
- [Error Templates (Interfaces) `new!`](#error-templates-interfaces-new)
- [Predefined elements for Functions (Atoms) `new!`](#predefined-elements-for-functions-atoms-new)
- [Install](#install)
- [TLDR (Only Most Important!)](#tldr-only-most-important)
- [Functions](#functions)
- [Types](#types)
- [Functions](#functions-1)
- [myError `♻️ Refactored`](#myerror-️-refactored)
- [myErrorWrapper `🎉 New feature!`](#myerrorwrapper--new-feature)
- [myErrorCatcher](#myerrorcatcher)
- [myErrorHandler](#myerrorhandler)
- [Types](#types-1)
- [TMyErrorList](#tmyerrorlist)
- [Error Templates (Interfaces) `new!`](#error-templates-interfaces-new)
- [Predefined elements for Functions (Atoms) `new!`](#predefined-elements-for-functions-atoms-new)

## Install

Expand Down Expand Up @@ -136,7 +136,7 @@ throw new myError(MyErrorList.BLACKLISTED, { message: ["nameInputed"] });

### myErrorWrapper `🎉 New feature!`

`trycatch` one line wrapper with instant error thrower.
`TryCatch` one line wrapper with instant error thrower.

```ts
// Before
Expand Down Expand Up @@ -165,6 +165,7 @@ const data = myErrorWrapper(readFile,new Error("Can't read file!"))("path...");
const data = await myErrorWrapper(asyncFun, new Error("Oh, Error!"))("MyString");
```


### myErrorCatcher

`new Promise` wrapper.
Expand All @@ -189,7 +190,7 @@ const MyErrorHandlerList = {
console.error("ERROR");
}
};
if (isError) await myErrorHandler(data.code, MyErrorHandlerList)();
if (isError) myErrorHandler(data.code, MyErrorHandlerList)();
```

## Types
Expand Down Expand Up @@ -245,4 +246,4 @@ Short predefined types to easy creating own Error types!
| [TErrorMessagesExt](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` | [TMyErrorList](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` | [TErrorList](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` |
| [TCauseError](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` | [TDetails](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` | [TBaseError](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` |
| [TBaseErrorExt](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` | [TValidationError](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` | [TApiError](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` |
| [TApiRateLimit](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` | | |
| [TApiRateLimit](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/errors.ts) `new!` | [StatusCodes](https://github.com/INeedJobToStartWork/MyError/blob/main/src/types/statusCodes.ts)`new!` | |
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "oh-my-error",
"version": "2.0.0-prerelease.1",
"version": "2.0.0-prerelease.2",
"description": "A simple error handler for nodejs",
"keywords": [
"error",
Expand Down
8 changes: 8 additions & 0 deletions src/functions/myError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@

import type { IMyError } from "@/types";

//----------------------
// Types
//----------------------

/**
* Represents an error object that may contain nested objects and functions.
*/
Expand All @@ -27,6 +31,10 @@ type ErrorArgs<T> = {
: T[K];
};

//----------------------
// Functions
//----------------------

/**
* Processes an error object, invoking functions with provided arguments
*
Expand Down
56 changes: 56 additions & 0 deletions src/functions/myErrorCatcher.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/* eslint-disable @typescript-eslint/require-await */
import { describe, expect, test } from "vitest";
import myErrorCatcher from "./myErrorCatcher";

describe("[FUNCTION] myErrorCatcher", () => {
describe("[ERRORS]", () => {
test("myErrorCatcher catch error and throw own error", () => {
const funThrowErr = () => {
throw new Error("Oh, it's Error!");
};

// eslint-disable-next-line vitest/valid-expect, @typescript-eslint/no-floating-promises, @typescript-eslint/promise-function-async
expect(() =>
myErrorCatcher(funThrowErr)().catch(() => {
throw new Error("Function Throws Error!");
})
).rejects.toThrowError("Function Throws Error!");
});
test("ASYNC myErrorCatcher catch error and throw own error", async () => {
const funThrowErr = async () => {
throw new Error("Oh, it's Error!");
};

// eslint-disable-next-line vitest/valid-expect, @typescript-eslint/no-floating-promises, @typescript-eslint/promise-function-async
expect(() =>
myErrorCatcher(funThrowErr)().catch(() => {
throw new Error("Function Throws Error!");
})
).rejects.toThrowError("Function Throws Error!");
});
});
describe("[PASS]", () => {
test("myErrorCatcher w", async () => {
const funReturnName = async (name: string) => name;

// eslint-disable-next-line vitest/valid-expect, @typescript-eslint/no-floating-promises, @typescript-eslint/promise-function-async
expect(
await myErrorCatcher(funReturnName)("John").catch(() => {
throw new Error("Function Throws Error!");
})
).toBe("John");
});
test("ASYNC myErrorCatcher catch error and throw own error", async () => {
const funThrowErr = async () => {
throw new Error("Oh, it's Error!");
};

// eslint-disable-next-line vitest/valid-expect, @typescript-eslint/no-floating-promises, @typescript-eslint/promise-function-async
expect(() =>
myErrorCatcher(funThrowErr)().catch(() => {
throw new Error("Function Throws Error!");
})
).rejects.toThrowError("Function Throws Error!");
});
});
});
21 changes: 19 additions & 2 deletions src/functions/myErrorCatcher.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,27 @@
import type { arrowFunction } from "@/types/internal";

/**
* Promise Wrapper.
*
*
* @param functionThatMayThrow - The error code to handle.
* @param errorSolutions - An object containing error handling functions, keyed by error codes.
*
* @returns `functionThatMayThrow` wrapped in Promise
*
* @example
* ```
* const data = await myErrorCatcher(readFile)("path...").catch(() => {
* // Code before crash...
* throw new Error("Can't read file!");
* });
* ```
*/
export const myErrorCatcher =
<T extends arrowFunction<T>>(functionThatMayThrow: T) =>
async (...arguments_: Parameters<T>): Promise<ReturnType<T>> =>
async (...args: Parameters<T>): Promise<ReturnType<T>> =>
new Promise(resolve => {
resolve(functionThatMayThrow(...arguments_));
resolve(functionThatMayThrow(...args));
});

export default myErrorCatcher;
19 changes: 15 additions & 4 deletions src/functions/myErrorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable @typescript-eslint/promise-function-async */
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
import { myError, myErrorWrapper } from "@/functions";
import type { TMyErrorList } from "@/types";

Expand Down Expand Up @@ -29,11 +27,24 @@ const ErrorList = {
* @param errorCode - The error code to handle.
* @param errorSolutions - An object containing error handling functions, keyed by error codes.
*
* @returns An async function that:
* @returns An sync function that:
* 1. Checks if the error code exists in the solutions.
* 2. If not, throws a "noKeyInList" error.
* 3. If it exists, executes the corresponding error solution function.
* 4. Wraps the execution in a try-catch block to handle any errors during execution.
* 4. Wraps the execution in a try-catch block (myErrorWrapper) to handle any errors during execution.
*
* @example
* ```
* const [data, isError] = myErrorWrapper(readFile)("./ReadThisFile");
*
* const MyErrorHandlerList = {
* FS001: () => {
* // Do this code if throw this error
* console.error("ERROR");
* }
* };
* if (isError) myErrorHandler(data.code, MyErrorHandlerList)();
* ```
*
*/
export const myErrorHandler =
Expand Down
21 changes: 19 additions & 2 deletions src/functions/myErrorWrapper.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
/* eslint-disable @typescript-eslint/promise-function-async */
/* eslint-disable @typescript-eslint/return-await */
import type { ErrorTypesCatched, TFunction, TIsPromise, UnwrapPromise } from "@/types/internal";

//----------------------
Expand All @@ -19,6 +17,24 @@ type MyErrorWrapperReturn<Fn extends AnyFunction, ErrorType = undefined> = Error
// Functions
//----------------------

/**
* TryCatch One line wrapper.
*
* @params errorToThrow - If `fnThatMayThrow` throw error, this will be instant throwed.
* @returns Tuple `[data,isError]`, with `errorToThrow` just `data`.
*
* @example
* ```
* // For Async add `await` before `myErrorWrapper`
* const [data,isError] = myErrorWrapper(readFile)("path...");
* if(isError) throw new Error("Can't read file!")
*
*
* // Or instant Error Throw (with errorToThrow)
*
* const data = myErrorWrapper(readFile,new Error("Can't read file!"))("path...");
* ```
*/
export const myErrorWrapper =
<Fn extends TFunction<Fn>, ErrorType = undefined>(
fnThatMayThrow: Fn,
Expand All @@ -27,6 +43,7 @@ export const myErrorWrapper =
(...args: Parameters<Fn>): MyErrorWrapperReturn<Fn, ErrorType> => {
const returnFNOutput = <G>(result: G) =>
(errorToThrow ? result : [result, false]) as MyErrorWrapperReturn<Fn, ErrorType>;

const returnError = (error: unknown) => {
if (errorToThrow) throw errorToThrow;
return [error as ErrorTypesCatched, true] as MyErrorWrapperReturn<Fn, ErrorType>;
Expand Down
38 changes: 37 additions & 1 deletion src/types/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ export type TSeverity = "ERROR" | "WARNING";
*/
export type TSeverity2 = "CRITICAL" | "HIGH" | "LOW" | "MEDIUM";

/**
* Predefined element for Custom Templates
*/
export type TErrorMessages =
| string
// eslint-disable-next-line @typescript-eslint/no-explicit-any
Expand Down Expand Up @@ -71,24 +74,33 @@ export type TErrorList<T> = {
};

/**
* Perfect for throwing catched error by trycatch
* Perfect for throwing catched error by TryCatch
*/
export type TCauseError = {
cause?: unknown;
};
export type TDetails<T = unknown> = {
details?: T;
};
/**
* Predefined element for Custom Templates
*/
export type TBaseError = {
message?: Parameters<typeof Error>[0];
options?: Parameters<typeof Error>[1];
};

/**
* Predefined Type for `Error`
*/
export type TBaseErrorExt = {
message?: TErrorMessages;
options?: TCauseError;
};

/**
* Predefined element for Custom Templates
*/
export type TValidationError = {
fields: Array<{
[K: string]: unknown;
Expand All @@ -102,13 +114,19 @@ export type TValidationError = {
}>;
};

/**
* Predefined element for Custom Templates
*/
export type TApiError = {
endpoint?: string;
path?: string;
status?: StatusCode | number;
timestamp?: Date;
};

/**
* Predefined element for Custom Templates
*/
export type TApiRateLimit = {
limit?: number;
remaining?: number;
Expand All @@ -117,15 +135,33 @@ export type TApiRateLimit = {
status?: StatusCode | number;
};

/**
* Basic Error Template for Error
* @author oh-my-error
*/
export interface IMyError {
code?: number | string;
hint?: TErrorMessagesExt;
message?: TErrorMessagesExt;
name?: string;
}

/**
* Basic Error Template for **API**
*/
export interface IMyErrorAPI extends IMyError, TApiError {}

/**
* Basic Error Template for **API Rate limit**
*/
export interface IMyErrorRateLimit extends IMyError, TApiRateLimit {}

/**
* Basic Error Template for **Validation**
*/
export interface IMyErrorValidation extends IMyError, TValidationError {}

/**
* Include Every Error Template
*/
export type TAllMyErrorTypes = IMyError | IMyErrorAPI | IMyErrorRateLimit | IMyErrorValidation;
Loading

0 comments on commit 4c9780c

Please sign in to comment.