I’m trying to implement global error handling using a gRPC server interceptor in grpc-js.
Below is my implementation:
function errorHandlingServerInterceptor(methodDescriptor, call) {
const listener = (new grpc.ServerListenerBuilder())
.withOnReceiveMetadata((metadata, next) => {
try {
next(metadata);
} catch (error) {
handleAndLogError(call, error);
}
})
.withOnReceiveMessage((message, next) => {
try {
next(message);
} catch (error) {
handleAndLogError(call, error);
}
})
.withOnReceiveHalfClose((next) => {
try {
next();
} catch (error) {
handleAndLogError(call, error);
}
})
.withOnCancel(() => {
logger.error(`Request was cancelled by the client.`);
})
.build();
const responder = (new grpc.ResponderBuilder())
.withStart(next => {
next(listener);
})
.withSendMetadata((metadata, next) => {
next(metadata);
})
.withSendMessage((message, next) => {
next(message);
})
.withSendStatus((status, next) => {
if (status.code !== grpc.status.OK) {
logger.error(`Error status code: ${status.code}, details: ${status.details}`);
}
next(status);
})
.build();
return new grpc.ServerInterceptingCall(call, responder);
}
I expected that errors thrown within the service methods would be caught by the try-catch blocks in the interceptor. However, this doesn’t seem to be happening. Can anyone explain why the errors thrown in service methods aren’t being caught and provide a solution to properly catch and handle these errors for global error handling?