diff --git a/packages/quicktype-core/src/language/CSharp/SystemTextJsonCSharpRenderer.ts b/packages/quicktype-core/src/language/CSharp/SystemTextJsonCSharpRenderer.ts index f3eccc8df4..2012326edd 100644 --- a/packages/quicktype-core/src/language/CSharp/SystemTextJsonCSharpRenderer.ts +++ b/packages/quicktype-core/src/language/CSharp/SystemTextJsonCSharpRenderer.ts @@ -375,8 +375,11 @@ export class SystemTextJsonCSharpRenderer extends CSharpRenderer { this.emitLine("case JsonTokenType.", tokenType, ":"); } - private emitThrow(message: Sourcelike): void { - this.emitLine("throw new Exception(", message, ");"); + private emitThrow( + exceptionType: "JsonException" | "NotSupportedException", + message: Sourcelike, + ): void { + this.emitLine("throw new ", exceptionType, "(", message, ");"); } private deserializeTypeCode(typeName: Sourcelike): Sourcelike { @@ -1239,7 +1242,7 @@ export class SystemTextJsonCSharpRenderer extends CSharpRenderer { (v) => this.emitLine("return ", v, ";"), ); if (!allHandled) { - this.emitThrow([ + this.emitThrow("JsonException", [ '"Cannot unmarshal type ', csType, '"', @@ -1266,7 +1269,7 @@ export class SystemTextJsonCSharpRenderer extends CSharpRenderer { () => this.emitLine("return;"), ); if (!allHandled) { - this.emitThrow([ + this.emitThrow("NotSupportedException", [ '"Cannot marshal type ', csType, '"', diff --git a/test/unit/csharp-system-text-json-exceptions.test.ts b/test/unit/csharp-system-text-json-exceptions.test.ts new file mode 100644 index 0000000000..04ddc339b7 --- /dev/null +++ b/test/unit/csharp-system-text-json-exceptions.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, test } from "vitest"; + +import { + InputData, + JSONSchemaInput, + quicktype, +} from "../../packages/quicktype-core/src/index.js"; + +async function renderSystemTextJsonCSharp(schema: object): Promise { + const schemaInput = new JSONSchemaInput(undefined); + await schemaInput.addSource({ + name: "TopLevel", + schema: JSON.stringify(schema), + }); + + const inputData = new InputData(); + inputData.addInput(schemaInput); + + const result = await quicktype({ + inputData, + lang: "csharp", + rendererOptions: { framework: "SystemTextJson" }, + }); + return result.lines.join("\n"); +} + +describe("C# System.Text.Json converters", () => { + test("throw serializer-supported exceptions for union conversion failures", async () => { + const output = await renderSystemTextJsonCSharp({ + type: "object", + properties: { + mixed: { oneOf: [{ type: "integer" }, { type: "string" }] }, + }, + required: ["mixed"], + }); + + expect(output).toContain( + 'throw new JsonException("Cannot unmarshal type Mixed");', + ); + expect(output).toContain( + 'throw new NotSupportedException("Cannot marshal type Mixed");', + ); + expect(output).not.toContain("throw new Exception("); + }); +});