Search in sources :

Example 1 with ErrorType

use of com.palantir.conjure.java.api.errors.ErrorType in project conjure-java by palantir.

the class ErrorGenerator method generateErrorTypesForNamespace.

private static JavaFile generateErrorTypesForNamespace(TypeMapper typeMapper, String conjurePackage, ErrorNamespace namespace, List<ErrorDefinition> errorTypeDefinitions) {
    ClassName className = errorTypesClassName(conjurePackage, namespace);
    // Generate ErrorType definitions
    List<FieldSpec> fieldSpecs = errorTypeDefinitions.stream().map(errorDef -> {
        CodeBlock initializer = CodeBlock.of("ErrorType.create(ErrorType.Code.$L, \"$L:$L\")", errorDef.getCode().get(), namespace.get(), errorDef.getErrorName().getName());
        FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(ClassName.get(ErrorType.class), CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, errorDef.getErrorName().getName()), Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL).initializer(initializer);
        errorDef.getDocs().ifPresent(docs -> fieldSpecBuilder.addJavadoc(docs.get()));
        return fieldSpecBuilder.build();
    }).collect(Collectors.toList());
    // Generate ServiceException factory methods
    List<MethodSpec> methodSpecs = errorTypeDefinitions.stream().flatMap(entry -> {
        MethodSpec withoutCause = generateExceptionFactory(typeMapper, entry, false);
        MethodSpec withCause = generateExceptionFactory(typeMapper, entry, true);
        return Stream.of(withoutCause, withCause);
    }).collect(Collectors.toList());
    // Generate ServiceException factory check methods
    List<MethodSpec> checkMethodSpecs = errorTypeDefinitions.stream().map(entry -> {
        String exceptionMethodName = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, entry.getErrorName().getName());
        String methodName = "throwIf" + entry.getErrorName().getName();
        String shouldThrowVar = "shouldThrow";
        MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName).addModifiers(Modifier.PUBLIC, Modifier.STATIC).addParameter(TypeName.BOOLEAN, shouldThrowVar);
        methodBuilder.addJavadoc("Throws a {@link ServiceException} of type $L when {@code $L} is true.\n", entry.getErrorName().getName(), shouldThrowVar);
        methodBuilder.addJavadoc("@param $L $L\n", shouldThrowVar, "Cause the method to throw when true");
        Streams.concat(entry.getSafeArgs().stream(), entry.getUnsafeArgs().stream()).forEach(arg -> {
            methodBuilder.addParameter(typeMapper.getClassName(arg.getType()), arg.getFieldName().get());
            methodBuilder.addJavadoc("@param $L $L", arg.getFieldName().get(), StringUtils.appendIfMissing(arg.getDocs().map(Javadoc::render).orElse(""), "\n"));
        });
        methodBuilder.addCode("if ($L) {", shouldThrowVar);
        methodBuilder.addCode("throw $L;", Expressions.localMethodCall(exceptionMethodName, Streams.concat(entry.getSafeArgs().stream(), entry.getUnsafeArgs().stream()).map(arg -> arg.getFieldName().get()).collect(Collectors.toList())));
        methodBuilder.addCode("}");
        return methodBuilder.build();
    }).collect(Collectors.toList());
    List<MethodSpec> isRemoteExceptionDefinitions = errorTypeDefinitions.stream().map(entry -> {
        String typeName = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, entry.getErrorName().getName());
        String methodName = "is" + entry.getErrorName().getName();
        return MethodSpec.methodBuilder(methodName).addModifiers(Modifier.PUBLIC, Modifier.STATIC).addParameter(RemoteException.class, REMOTE_EXCEPTION_VAR).returns(TypeName.BOOLEAN).addStatement(Expressions.requireNonNull(REMOTE_EXCEPTION_VAR, "remote exception must not be null")).addStatement("return $N.name().equals($N.getError().errorName())", typeName, REMOTE_EXCEPTION_VAR).addJavadoc("Returns true if the {@link $T} is named $L:$L", RemoteException.class, entry.getNamespace(), entry.getErrorName().getName()).build();
    }).collect(Collectors.toList());
    TypeSpec.Builder typeBuilder = TypeSpec.classBuilder(className).addMethod(privateConstructor()).addModifiers(Modifier.PUBLIC, Modifier.FINAL).addFields(fieldSpecs).addMethods(methodSpecs).addMethods(checkMethodSpecs).addMethods(isRemoteExceptionDefinitions).addAnnotation(ConjureAnnotations.getConjureGeneratedAnnotation(ErrorGenerator.class));
    return JavaFile.builder(conjurePackage, typeBuilder.build()).skipJavaLangImports(true).indent("    ").build();
}
Also used : ErrorDefinition(com.palantir.conjure.spec.ErrorDefinition) Modifier(javax.lang.model.element.Modifier) Javadoc(com.palantir.conjure.java.util.Javadoc) TypeFunctions(com.palantir.conjure.java.util.TypeFunctions) FieldSpec(com.squareup.javapoet.FieldSpec) ClassName(com.squareup.javapoet.ClassName) HashMap(java.util.HashMap) ConjureDefinition(com.palantir.conjure.spec.ConjureDefinition) StringUtils(org.apache.commons.lang3.StringUtils) Options(com.palantir.conjure.java.Options) ArrayList(java.util.ArrayList) SafeArg(com.palantir.logsafe.SafeArg) Generator(com.palantir.conjure.java.Generator) Map(java.util.Map) ErrorNamespace(com.palantir.conjure.spec.ErrorNamespace) RemoteException(com.palantir.conjure.java.api.errors.RemoteException) CodeBlock(com.squareup.javapoet.CodeBlock) TypeDefinition(com.palantir.conjure.spec.TypeDefinition) CaseFormat(com.google.common.base.CaseFormat) MethodSpec(com.squareup.javapoet.MethodSpec) Packages(com.palantir.conjure.java.util.Packages) ErrorType(com.palantir.conjure.java.api.errors.ErrorType) Streams(com.google.common.collect.Streams) ServiceException(com.palantir.conjure.java.api.errors.ServiceException) FieldDefinition(com.palantir.conjure.spec.FieldDefinition) TypeSpec(com.squareup.javapoet.TypeSpec) Collectors(java.util.stream.Collectors) JavaFile(com.squareup.javapoet.JavaFile) List(java.util.List) Stream(java.util.stream.Stream) UnsafeArg(com.palantir.logsafe.UnsafeArg) ConjureAnnotations(com.palantir.conjure.java.ConjureAnnotations) TypeName(com.squareup.javapoet.TypeName) MethodSpec(com.squareup.javapoet.MethodSpec) CodeBlock(com.squareup.javapoet.CodeBlock) Javadoc(com.palantir.conjure.java.util.Javadoc) FieldSpec(com.squareup.javapoet.FieldSpec) ErrorType(com.palantir.conjure.java.api.errors.ErrorType) ClassName(com.squareup.javapoet.ClassName) TypeSpec(com.squareup.javapoet.TypeSpec)

Example 2 with ErrorType

use of com.palantir.conjure.java.api.errors.ErrorType in project conjure-java-runtime-api by palantir.

the class RemoteExceptionAssertTest method testSanity.

@Test
public void testSanity() throws Exception {
    ErrorType actualType = ErrorType.FAILED_PRECONDITION;
    SerializableError error = SerializableError.forException(new ServiceException(actualType));
    Assertions.assertThat(new RemoteException(error, actualType.httpErrorCode())).isGeneratedFromErrorType(actualType);
    assertThatThrownBy(() -> Assertions.assertThat(new RemoteException(error, actualType.httpErrorCode() + 1)).isGeneratedFromErrorType(actualType)).isInstanceOf(AssertionError.class).hasMessage("Expected error status to be %s, but found %s", actualType.httpErrorCode(), actualType.httpErrorCode() + 1);
}
Also used : ErrorType(com.palantir.conjure.java.api.errors.ErrorType) ServiceException(com.palantir.conjure.java.api.errors.ServiceException) SerializableError(com.palantir.conjure.java.api.errors.SerializableError) RemoteException(com.palantir.conjure.java.api.errors.RemoteException) Test(org.junit.jupiter.api.Test)

Example 3 with ErrorType

use of com.palantir.conjure.java.api.errors.ErrorType in project conjure-java-runtime by palantir.

the class JsonExceptionMapper method toResponseInner.

@Override
public final Response toResponseInner(T exception) {
    String errorInstanceId = UUID.randomUUID().toString();
    ErrorType errorType = getErrorType(exception);
    if (errorType.httpErrorCode() / 100 == 4) /* client error */
    {
        log.info("Error handling request. {}: {}", SafeArg.of("errorName", errorType.name()), SafeArg.of("errorInstanceId", errorInstanceId), exception);
    } else {
        log.error("Error handling request. {}: {}", SafeArg.of("errorName", errorType.name()), SafeArg.of("errorInstanceId", errorInstanceId), exception);
    }
    return createResponse(errorType, errorInstanceId);
}
Also used : ErrorType(com.palantir.conjure.java.api.errors.ErrorType)

Example 4 with ErrorType

use of com.palantir.conjure.java.api.errors.ErrorType in project conjure-java-runtime-api by palantir.

the class ServiceExceptionAssertTest method testSanity.

@Test
public void testSanity() {
    ErrorType actualType = ErrorType.FAILED_PRECONDITION;
    Assertions.assertThat(new ServiceException(actualType, SafeArg.of("a", "b"), UnsafeArg.of("c", "d"))).hasType(actualType).hasArgs(SafeArg.of("a", "b"), UnsafeArg.of("c", "d"));
    Assertions.assertThat(new ServiceException(actualType, SafeArg.of("a", "b"), UnsafeArg.of("c", "d"))).hasType(actualType).hasArgs(UnsafeArg.of("c", "d"), // Order doesn't matter
    SafeArg.of("a", "b"));
    Assertions.assertThat(new ServiceException(actualType)).hasNoArgs();
    assertThatThrownBy(() -> Assertions.assertThat(new ServiceException(actualType)).hasType(ErrorType.INTERNAL)).isInstanceOf(AssertionError.class).hasMessage("Expected ErrorType to be %s, but found %s", ErrorType.INTERNAL, actualType);
    assertThatThrownBy(() -> Assertions.assertThat(new ServiceException(actualType, SafeArg.of("a", "b"))).hasArgs(SafeArg.of("c", "d"))).isInstanceOf(AssertionError.class).hasMessage("Expected safe args to be {c=d}, but found {a=b}");
    assertThatThrownBy(() -> Assertions.assertThat(new ServiceException(actualType, UnsafeArg.of("a", "b"))).hasArgs(UnsafeArg.of("c", "d"))).isInstanceOf(AssertionError.class).hasMessage("Expected unsafe args to be {c=d}, but found {a=b}");
    assertThatThrownBy(() -> Assertions.assertThat(new ServiceException(actualType, SafeArg.of("a", "b"))).hasNoArgs()).isInstanceOf(AssertionError.class).hasMessage("Expected no args, but found {a=b}");
    assertThatThrownBy(() -> Assertions.assertThat(new ServiceException(actualType, SafeArg.of("a", "b"), UnsafeArg.of("c", "d"))).hasNoArgs()).isInstanceOf(AssertionError.class).hasMessage("Expected no args, but found {a=b, c=d}");
    Assertions.assertThat(new ServiceException(actualType, UnsafeArg.of("a", "b"), UnsafeArg.of("c", "d"))).containsArgs(UnsafeArg.of("a", "b"));
    // Safety matters
    assertThatThrownBy(() -> Assertions.assertThat(new ServiceException(actualType, SafeArg.of("a", "b"), UnsafeArg.of("c", "d"))).containsArgs(UnsafeArg.of("a", "b"))).isInstanceOf(AssertionError.class).hasMessage("Expected unsafe args to contain {a=b}, but found {c=d}");
    assertThatThrownBy(() -> Assertions.assertThat(new ServiceException(actualType, SafeArg.of("a", "b"))).containsArgs(SafeArg.of("c", "d"))).isInstanceOf(AssertionError.class).hasMessage("Expected safe args to contain {c=d}, but found {a=b}");
    assertThatThrownBy(() -> Assertions.assertThat(new ServiceException(actualType, UnsafeArg.of("a", "b"))).containsArgs(UnsafeArg.of("c", "d"))).isInstanceOf(AssertionError.class).hasMessage("Expected unsafe args to contain {c=d}, but found {a=b}");
}
Also used : ErrorType(com.palantir.conjure.java.api.errors.ErrorType) ServiceException(com.palantir.conjure.java.api.errors.ServiceException) Test(org.junit.jupiter.api.Test)

Aggregations

ErrorType (com.palantir.conjure.java.api.errors.ErrorType)4 ServiceException (com.palantir.conjure.java.api.errors.ServiceException)3 RemoteException (com.palantir.conjure.java.api.errors.RemoteException)2 Test (org.junit.jupiter.api.Test)2 CaseFormat (com.google.common.base.CaseFormat)1 Streams (com.google.common.collect.Streams)1 ConjureAnnotations (com.palantir.conjure.java.ConjureAnnotations)1 Generator (com.palantir.conjure.java.Generator)1 Options (com.palantir.conjure.java.Options)1 SerializableError (com.palantir.conjure.java.api.errors.SerializableError)1 Javadoc (com.palantir.conjure.java.util.Javadoc)1 Packages (com.palantir.conjure.java.util.Packages)1 TypeFunctions (com.palantir.conjure.java.util.TypeFunctions)1 ConjureDefinition (com.palantir.conjure.spec.ConjureDefinition)1 ErrorDefinition (com.palantir.conjure.spec.ErrorDefinition)1 ErrorNamespace (com.palantir.conjure.spec.ErrorNamespace)1 FieldDefinition (com.palantir.conjure.spec.FieldDefinition)1 TypeDefinition (com.palantir.conjure.spec.TypeDefinition)1 SafeArg (com.palantir.logsafe.SafeArg)1 UnsafeArg (com.palantir.logsafe.UnsafeArg)1