Skip to content

Commit

Permalink
Merge pull request #1832 from riganti/fix-CoerceError-message
Browse files Browse the repository at this point in the history
JS: make CoerceError inherit Error, fixing console log
  • Loading branch information
exyi authored Jun 22, 2024
2 parents 9d053d0 + 8581b83 commit 438bd02
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 @@ -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();
})

0 comments on commit 438bd02

Please sign in to comment.