Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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,
'"',
Expand All @@ -1266,7 +1269,7 @@ export class SystemTextJsonCSharpRenderer extends CSharpRenderer {
() => this.emitLine("return;"),
);
if (!allHandled) {
this.emitThrow([
this.emitThrow("NotSupportedException", [
'"Cannot marshal type ',
csType,
'"',
Expand Down
45 changes: 45 additions & 0 deletions test/unit/csharp-system-text-json-exceptions.test.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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(");
});
});
Loading