Made SoftError for recoverable errors

This commit is contained in:
Kir_Antipov 2023-01-10 08:36:26 +00:00
parent 3fe2a3fdc9
commit 3f8d7d2115
2 changed files with 89 additions and 0 deletions

View file

@ -0,0 +1,40 @@
/**
* Represents a soft error, indicating whether the error is recoverable or not.
*/
export class SoftError extends Error {
/**
* Indicates whether the error is recoverable or not.
*/
private readonly _isSoft: boolean;
/**
* Initializes a new instance of the {@link SoftError} class.
*
* @param isSoft - Indicates whether the error is recoverable or not.
* @param message - An optional error message.
*/
constructor(isSoft: boolean, message?: string) {
super(message);
this.name = "SoftError";
this._isSoft = isSoft;
}
/**
* Indicates whether the error is recoverable or not.
*/
get isSoft(): boolean {
return this._isSoft;
}
}
/**
* Determines whether the specified error is a soft error.
*
* @param error - The error to check.
*
* @returns `true` if the error is soft (i.e., recoverable); otherwise, `false`.
*/
export function isSoftError(error: unknown): boolean {
return !!(error as SoftError)?.isSoft;
}

View file

@ -0,0 +1,49 @@
import { SoftError, isSoftError } from "@/utils/errors/soft-error";
describe("SoftError", () => {
describe("constructor", () => {
test("initializes with isSoft set to false", () => {
const error = new SoftError(false, "An error occurred.");
expect(error).toBeInstanceOf(SoftError);
expect(error.name).toBe("SoftError");
expect(error.message).toBe("An error occurred.");
expect(error.isSoft).toBe(false);
});
test("initializes with isSoft set to true", () => {
const error = new SoftError(true, "An error occurred.");
expect(error).toBeInstanceOf(SoftError);
expect(error.name).toBe("SoftError");
expect(error.message).toBe("An error occurred.");
expect(error.isSoft).toBe(true);
});
});
});
describe("isSoftError", () => {
test("returns true for SoftError with isSoft set to true", () => {
const error = new SoftError(true, "An error occurred.");
expect(isSoftError(error)).toBe(true);
});
test("returns false for SoftError with isSoft set to false", () => {
const error = new SoftError(false, "An error occurred.");
expect(isSoftError(error)).toBe(false);
});
test("returns false for non-SoftError errors", () => {
const error = new Error("An error occurred.");
expect(isSoftError(error)).toBe(false);
});
test("returns false for non-error values", () => {
expect(isSoftError("string")).toBe(false);
expect(isSoftError(123)).toBe(false);
expect(isSoftError({ key: "value" })).toBe(false);
});
});