Skip to content

Commit

Permalink
JS: make CoerceError inherit Error, fixing console log
Browse files Browse the repository at this point in the history
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
  • Loading branch information
exyi committed Jun 22, 2024
1 parent cbe4d5e commit 0097140
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/Framework/Framework/Resources/Scripts/shared-classes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}'.`);
Expand Down
19 changes: 18 additions & 1 deletion src/Framework/Framework/Resources/Scripts/tests/coercer.test.ts
Original file line number Diff line number Diff line change
@@ -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({
Expand Down Expand Up @@ -619,3 +620,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();
})

0 comments on commit 0097140

Please sign in to comment.