From 8581b8386c964faf4427247041a2df418469f6a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Standa=20Luke=C5=A1?= Date: Fri, 21 Jun 2024 23:57:29 +0200 Subject: [PATCH] JS: make CoerceError inherit Error, fixing console log JavaScript is happy throwing any objects, but it doesn't neccessarily show it well in the console (Only something like "Uncaught {...}"). When the class extends error, it has the correct toString conversion Resolves #1831 --- .../Resources/Scripts/shared-classes.ts | 6 ++++-- .../Resources/Scripts/tests/coercer.test.ts | 19 ++++++++++++++++++- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/Framework/Framework/Resources/Scripts/shared-classes.ts b/src/Framework/Framework/Resources/Scripts/shared-classes.ts index 5d094f2d53..ea8e8c8281 100644 --- a/src/Framework/Framework/Resources/Scripts/shared-classes.ts +++ b/src/Framework/Framework/Resources/Scripts/shared-classes.ts @@ -4,13 +4,15 @@ export class DotvvmPostbackError { toString() { return "PostbackRejectionError(" + JSON.stringify(this.reason, null, " ") + ")"} } -export class CoerceError implements CoerceErrorType { +export class CoerceError extends Error implements CoerceErrorType { isError: true = true wasCoerced: false = false get value(): never { throw this } - constructor(public message: string, public path: string = "") { + constructor(message: string, public path: string = "") { + super(message) + this.name = "CoerceError" } public static generic(value: any, type: TypeDefinition) { return new CoerceError(`Cannot coerce '${value}' to type '${type}'.`); diff --git a/src/Framework/Framework/Resources/Scripts/tests/coercer.test.ts b/src/Framework/Framework/Resources/Scripts/tests/coercer.test.ts index 41712b5e26..2cb8edf63d 100644 --- a/src/Framework/Framework/Resources/Scripts/tests/coercer.test.ts +++ b/src/Framework/Framework/Resources/Scripts/tests/coercer.test.ts @@ -1,5 +1,6 @@ -import { tryCoerce } from "../metadata/coercer" +import { coerce, tryCoerce } from "../metadata/coercer" import { formatTypeName } from "../metadata/typeMap"; +import { CoerceError } from "../shared-classes"; import { initDotvvm } from "./helper"; initDotvvm({ @@ -639,3 +640,19 @@ test("formatTypeName", () => { expect(formatTypeName({ type: "nullable", inner: "t2" })).toBe("t2?"); expect(formatTypeName([ { type:"nullable", inner: [ [ "t1" ] ] }])).toBe("MyType1[][]?[] (t1[][]?[])"); }) + + +test("Exception - inherits Error", () => { + let hasError = false; + try { + coerce("something", "Int32") + } catch (e: any) { + hasError = true; + expect(e instanceof Error).toBeTruthy(); + expect(e instanceof CoerceError).toBeTruthy(); + expect(e.message).toBe("Cannot coerce 'something' to type 'Int32'."); + expect(e.name).toBe("CoerceError"); + expect("" + e).toBe("CoerceError: Cannot coerce 'something' to type 'Int32'."); + } + expect(hasError).toBeTruthy(); +})