Skip to content

Add generated error types for convenience #298

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 6, 2021
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 @@ -306,6 +306,7 @@ public Void serviceShape(ServiceShape shape) {

if (settings.generateServerSdk()) {
generateServiceInterface(shape);
generateServerErrors(shape);
}

if (protocolGenerator != null) {
Expand Down Expand Up @@ -397,6 +398,19 @@ private void generateServiceInterface(ServiceShape shape) {
});
}

private void generateServerErrors(ServiceShape service) {
TopDownIndex.of(model)
.getContainedOperations(service)
.stream()
.flatMap(o -> o.getErrors().stream())
.distinct()
.map(id -> model.expectShape(id).asStructureShape().orElseThrow(IllegalArgumentException::new))
.sorted()
.forEachOrdered(error -> writers.useShapeWriter(service, serverSymbolProvider, writer -> {
new ServerErrorGenerator(settings, model, error, serverSymbolProvider, writer).run();
}));
}

private void generateCommands(ServiceShape shape) {
// Generate each operation for the service.
TopDownIndex topDownIndex = TopDownIndex.of(model);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/

package software.amazon.smithy.typescript.codegen;

import software.amazon.smithy.codegen.core.Symbol;
import software.amazon.smithy.codegen.core.SymbolProvider;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.traits.ErrorTrait;

/**
* Generates convenience error types for servers, since service developers will throw a modeled exception directly,
* while clients typically care only about catching them.
*/
final class ServerErrorGenerator implements Runnable {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should add a comment explaining why this is here, particularly when it's not being done for clients.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

okay, I added it


private final TypeScriptSettings settings;
private final Model model;
private final StructureShape errorShape;
private final SymbolProvider symbolProvider;
private final TypeScriptWriter writer;

ServerErrorGenerator(TypeScriptSettings settings,
Model model,
StructureShape errorShape,
SymbolProvider symbolProvider,
TypeScriptWriter writer) {
this.settings = settings;
this.model = model;
this.errorShape = errorShape;
this.symbolProvider = symbolProvider;
this.writer = writer;
}


@Override
public void run() {
Symbol symbol = symbolProvider.toSymbol(errorShape);

// Did not add this as a symbol to the error shape since these should not be used by anyone but the user.
String typeName = symbol.getName() + "Error";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is suffixing errors being used to get around having to alias the error interface? It would probably be better to construct a SymbolReference for the error like so:

SymbolReference symbol = SymbolReference.builder()
    .symbol(errorInterfaceSymbol)
    .alias("__" + errorInterfaceSymbol.getName())
    .build();

Of course you could also do:

String errorInterfaceAlias = "__" + errorInterfaceSymbol.getName();
writer.addImport(errorInterfaceSymbol, errorInterfaceAlias, SymbolReference.ContextOption.USE);

And then manually pass around the name string, which is effectively what the SymbolReference gives you.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is to work around the fact that we can't export the type from models and then export a type of the same name here. Honestly, it works out; instead of throwing new ResourceNotFound(), you throw new ResourceNotFoundError(), and people will probably figure out that they don't want to postfix their error structure names with Error.


writer.openBlock("export class $L implements $T {", "}",
typeName,
symbol,
() -> {

writer.write("readonly name = $S;", errorShape.getId().getName());
writer.write("readonly $$fault = $S;", errorShape.expectTrait(ErrorTrait.class).getValue());
//TODO: remove me when we fix where $metadata goes
writer.write("readonly $$metadata = {};");
if (!errorShape.members().isEmpty()) {
writer.write("");
StructuredMemberWriter structuredMemberWriter = new StructuredMemberWriter(
model, symbolProvider, errorShape.getAllMembers().values());
structuredMemberWriter.writeMembers(writer, errorShape);
writer.write("");
structuredMemberWriter.writeConstructor(writer, errorShape);
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,26 @@ void writeMemberFilterSensitiveLog(TypeScriptWriter writer, MemberShape member,
}
}

/**
* Writes a constructor function that takes in an object allowing modeled fields to be initialized.
*/
void writeConstructor(TypeScriptWriter writer, Shape shape) {
writer.openBlock("constructor(opts: {", "}) {", () -> {
writeMembers(writer, shape);
});
writer.indent();

for (MemberShape member : members) {
if (skipMembers.contains(member.getMemberName())) {
continue;
}

writer.write("this.${1L} = opts.${1L};", getSanitizedMemberName(member));
}

writer.closeBlock("}");
}

/**
* Writes SENSITIVE_STRING to hide the value of sensitive members.
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ public void generateFrameworkErrorSerializer(GenerationContext inputContext) {
writeEmptyEndpoint(context);

writer.openBlock("switch (input.name) {", "}", () -> {
for (final Shape shape : context.getModel().getShapesWithTrait(HttpErrorTrait.class)) {
for (final Shape shape : new TreeSet<>(context.getModel().getShapesWithTrait(HttpErrorTrait.class))) {
StructureShape errorShape = shape.asStructureShape().orElseThrow(IllegalArgumentException::new);
writer.openBlock("case $S: {", "}", errorShape.getId().getName(), () -> {
generateErrorSerializationImplementation(context, errorShape, responseType, bindingIndex);
Expand Down