mirror of
https://github.com/pybricks/pybricks-code.git
synced 2026-09-15 02:54:07 +00:00
src/utils: add ensureError() function
Typescript v4.4 no longer assumes that the error in catch is an Error object [1]. This adds a helper function to ensure that caught errors at least match the Error interface. If not, it creates a new Error object with the value as the message. [1]: https://devblogs.microsoft.com/typescript/announcing-typescript-4-4-beta/#using-unknown-in-catch-variables
This commit is contained in:
committed by
David Lechner
parent
79db359398
commit
e7d44ea9a9
+11
-1
@@ -1,7 +1,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
// Copyright (c) 2020 The Pybricks Authors
|
||||
|
||||
import { assert, defined, hex, maybe } from '.';
|
||||
import { assert, defined, ensureError, hex, maybe } from '.';
|
||||
|
||||
test('assert', () => {
|
||||
const assertTrue = jest.fn(() => assert(true, 'should not throw'));
|
||||
@@ -34,3 +34,13 @@ test('hex', () => {
|
||||
expect(hex(1, 4)).toBe('0x0001');
|
||||
expect(hex(2, 8)).toBe('0x00000002');
|
||||
});
|
||||
|
||||
test('ensureError', () => {
|
||||
const err = new Error('test error');
|
||||
expect(ensureError(err)).toBe(err);
|
||||
|
||||
const stringToErrorMessage = 'not an Error';
|
||||
const stringToError = expect(ensureError(stringToErrorMessage));
|
||||
stringToError.toHaveProperty('name', 'Error');
|
||||
stringToError.toHaveProperty('message', stringToErrorMessage);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user