aboutsummaryrefslogtreecommitdiff
path: root/src/utils
diff options
context:
space:
mode:
authorGravatar Corentin Thomasset <corentin.thomasset74@gmail.com> 2022-12-07 21:52:24 +0100
committerGravatar Corentin Thomasset <corentin.thomasset74@gmail.com> 2022-12-07 21:52:24 +0100
commit8476cf319b7ebae87c7928592604a54833ac56ef (patch)
treea13b04dc2ee1b56a183ae562050540cb17bd2334 /src/utils
parent0ff853437bacc2e027a1606b84d7a6f361e818e6 (diff)
downloadit-tools-8476cf319b7ebae87c7928592604a54833ac56ef.tar.gz
it-tools-8476cf319b7ebae87c7928592604a54833ac56ef.tar.zst
it-tools-8476cf319b7ebae87c7928592604a54833ac56ef.zip
fix(integer-base-converter): handle non-decimal char and better error message
Diffstat (limited to 'src/utils')
-rw-r--r--src/utils/error.test.ts29
-rw-r--r--src/utils/error.ts24
2 files changed, 53 insertions, 0 deletions
diff --git a/src/utils/error.test.ts b/src/utils/error.test.ts
new file mode 100644
index 0000000..0272804
--- /dev/null
+++ b/src/utils/error.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, it } from 'vitest';
+import { getErrorMessageIfThrows } from './error';
+
+describe('error util', () => {
+ describe('getErrorMessageIfThrows', () => {
+ it('get an error message if the callback throws, undefined instead', () => {
+ expect(
+ getErrorMessageIfThrows(() => {
+ throw 'message';
+ }),
+ ).to.equal('message');
+
+ expect(
+ getErrorMessageIfThrows(() => {
+ throw new Error('message');
+ }),
+ ).to.equal('message');
+
+ expect(
+ getErrorMessageIfThrows(() => {
+ throw { message: 'message' };
+ }),
+ ).to.equal('message');
+
+ // eslint-disable-next-line @typescript-eslint/no-empty-function
+ expect(getErrorMessageIfThrows(() => {})).to.equal(undefined);
+ });
+ });
+});
diff --git a/src/utils/error.ts b/src/utils/error.ts
new file mode 100644
index 0000000..681db91
--- /dev/null
+++ b/src/utils/error.ts
@@ -0,0 +1,24 @@
+import _ from 'lodash';
+
+export { getErrorMessageIfThrows };
+
+function getErrorMessageIfThrows(cb: () => unknown) {
+ try {
+ cb();
+ return undefined;
+ } catch (err) {
+ if (_.isString(err)) {
+ return err;
+ }
+
+ if (_.isError(err)) {
+ return err.message;
+ }
+
+ if (_.isObject(err) && _.has(err, 'message')) {
+ return (err as { message: string }).message;
+ }
+
+ return 'An error as occurred.';
+ }
+}