mirror of
https://github.com/CorentinTh/it-tools.git
synced 2025-06-17 03:34:58 -04:00
fix(integer-base-converter): handle non-decimal char and better error message
This commit is contained in:
parent
0ff853437b
commit
8476cf319b
4 changed files with 93 additions and 11 deletions
29
src/utils/error.test.ts
Normal file
29
src/utils/error.test.ts
Normal file
|
@ -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);
|
||||
});
|
||||
});
|
||||
});
|
24
src/utils/error.ts
Normal file
24
src/utils/error.ts
Normal file
|
@ -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.';
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue