Move exception handling into autoconfiguration

This commit is contained in:
Dave Syer
2024-11-21 15:49:46 +00:00
parent c239cfe970
commit 3feca42834
7 changed files with 95 additions and 10 deletions

View File

@@ -3,10 +3,8 @@ package org.springframework.grpc.sample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.grpc.server.GlobalServerInterceptor;
import org.springframework.grpc.server.exception.GrpcExceptionHandlerInterceptor;
import org.springframework.grpc.server.exception.GrpcExceptionHandler;
import io.grpc.ServerInterceptor;
import io.grpc.Status;
@SpringBootApplication
@@ -16,15 +14,14 @@ public class GrpcServerApplication {
SpringApplication.run(GrpcServerApplication.class, args);
}
@GlobalServerInterceptor
@Bean
public ServerInterceptor globalInterceptor() {
return new GrpcExceptionHandlerInterceptor(exception -> {
public GrpcExceptionHandler globalInterceptor() {
return exception -> {
if (exception instanceof IllegalArgumentException) {
return Status.INVALID_ARGUMENT.withDescription(exception.getMessage());
}
return null;
});
};
}
}

View File

@@ -82,6 +82,32 @@ class GrpcServerIntegrationTests {
}
@Nested
@SpringBootTest("spring.grpc.server.exception-handler.enabled=false")
class ServerWithUnhandledException {
@Test
void specificErrorResponse(@Autowired GrpcChannelFactory channels) {
SimpleGrpc.SimpleBlockingStub client = SimpleGrpc
.newBlockingStub(channels.createChannel("0.0.0.0:0").build());
assertThat(assertThrows(StatusRuntimeException.class,
() -> client.sayHello(HelloRequest.newBuilder().setName("error").build()))
.getStatus()
.getCode()).isEqualTo(Code.UNKNOWN);
}
@Test
void defaultErrorResponseIsUnknown(@Autowired GrpcChannelFactory channels) {
SimpleGrpc.SimpleBlockingStub client = SimpleGrpc
.newBlockingStub(channels.createChannel("0.0.0.0:0").build());
assertThat(assertThrows(StatusRuntimeException.class,
() -> client.sayHello(HelloRequest.newBuilder().setName("internal").build()))
.getStatus()
.getCode()).isEqualTo(Code.UNKNOWN);
}
}
@Nested
@SpringBootTest(properties = { "spring.grpc.server.host=0.0.0.0", "spring.grpc.server.port=0",
"spring.grpc.inprocess.enabled=false" })