How to send exception caught in gRPC C# server Error Interceptor to TypeScript gRPC-Web client?

Viewed 1290

I need to sent custom exceptions message to client. I have the following code:

  • in Startup.cs ConfigureServices method
services.AddGrpc(options => options.Interceptors.Add<ErrorInterceptor>());
  • in ErrorInterceptor.cs
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(TRequest request, ServerCallContext context, UnaryServerMethod<TRequest, TResponse> continuation)
{
    try
    {
        return await continuation(request, context);
    }
    catch (ValidationException validationExc)
    {
        await WriteResponseHeadersAsync(StatusCode.InvalidArgument, translation =>
             translation.GetEnumTranslation(validationExc.Error, validationExc.Parameters));
    }
    catch (Exception)
    {
        await WriteResponseHeadersAsync(StatusCode.Internal, translation =>
             translation.GetEnumTranslation(HttpStatusCode.InternalServerError));
    }
    return default;

    Task WriteResponseHeadersAsync(StatusCode statusCode, Func<ITranslationService, string> getMessage)
    {
        var httpContext = context.GetHttpContext();
        var translationService = httpContext.RequestServices.GetService<ITranslationService>();
        var errorMessage = getMessage(translationService);
        var responseHeaders = new Metadata
        {
            { nameof(errorMessage) , errorMessage },//1) can see in browser's devTools, but not in the code
            { "content-type" , errorMessage },//2) ugly, but works
        };
        context.Status = new Status(statusCode, errorMessage);//3) not working
        return context.WriteResponseHeadersAsync(responseHeaders);//4) alternative?
    }
}
  • in mask-http.service.ts
    this.grpcClient.add(request, (error, reply: MaskInfoReply) => {
        this.grpcBaseService.handleResponse<MaskInfoReply.AsObject>(error, reply, response => {
            const mask = new Mask(response.id, response.name);
            callback(mask);
        });
    });
  • in grpc-base.service.ts
    handleResponse<T>(error: ServiceError,
        reply: {
            toObject(includeInstance?: boolean): T;
        },
        func: (response: T) => void) {

        if (error) {
            const errorMessage = error.metadata.headersMap['content-type'][0];
            this.toasterService.openSnackBar(errorMessage, "Ok");
            console.error(error);
            return;
        }
        const response = reply.toObject();
        func(response);
    }
  1. I wanted to send error using Status (comment 3), but it doesn't get changed
  2. I wonder if there is an alternative way to send it not in response headers (comment 4)
  3. I tried to add custom response header (comment 1), but the only one I received in client code was 'content-type' so I decided to overwrite it (comment 2)
1 Answers

I hit the same dead end recently and decided to do it this way:

  1. Create an error model:

    message ValidationErrorDto {
        // A path leading to a field in the request body.
        string field = 1;
    
        // A description of why the request element is bad.
        string description = 2;
    }
    
    message ErrorSynopsisDto {
      string traceTag = 1;
      repeated ValidationErrorDto validationErrors = 2;
    }
    
  2. Create an extension for the error model that serializes the object to JSON:

    using Newtonsoft.Json;
    using Newtonsoft.Json.Serialization;
    
    public static class ErrorSynopsisDtoExtension
    {
        public static string ToJson(this ErrorSynopsisDto errorSynopsisDto) =>
        JsonConvert.SerializeObject(
            errorSynopsisDto,
            new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            });
    }
    
  3. Create a custom exception that encapsulates error model:

    public class OperationException : Exception
    {
        private readonly List<ValidationErrorDto> validationErrors = new();
        public bool HasValidationErrors => this.validationErrors.Count > 0;
    
        public OperationException(string traceTag) : base
            (
                new ErrorSynopsisDto
                {
                    TraceTag = traceTag
                }.ToJson() // <- here goes that extension
            ) => ErrorTag = traceTag;
    
        public OperationException(
            string traceTag,
            List<ValidationErrorDto> validationErrors
        ) : base
            (
                new ErrorSynopsisDto
                {
                    TraceTag = traceTag,
                    ValidationErrors = { validationErrors }
                }.ToJson() // <- here goes that extension again
            )
        {
            ErrorTag = traceTag;
            this.validationErrors = validationErrors;
        }
    }
    
  4. Throw custom exception from service call handlers:

    throw new OperationException(
        "MY_CUSTOM_VALIDATION_ERROR_CODE",
        // the following block can be simplified with a mapper, for reduced boilerplate
        new()
        {
            new()
            {
                Field = "Profile.FirstName",
                Description = "Is Required."
            }
        }
    );
    
  5. And lastly, the exception interceptor:

    public class ExceptionInterceptor : Interceptor
    {
        private readonly ILogger<ExceptionInterceptor> logger;
    
        public ExceptionInterceptor(ILogger<ExceptionInterceptor> logger) => this.logger = logger;
    
        public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
            TRequest request,
            ServerCallContext context,
            UnaryServerMethod<TRequest, TResponse> continuation
        )
        {
            try
            {
                return await continuation(request, context);
            }
            catch (OperationException ex)
            {
                this.logger.LogError(ex, context.Method);
                var httpContext = context.GetHttpContext();
    
                if (ex.HasValidationErrors)
                {
                    httpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
                }
                else
                {
                    httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                }
    
                throw;
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, context.Method);
                var httpContext = context.GetHttpContext();
                httpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                var opEx = new OperationException("MY_CUSTOM_INTERNAL_ERROR_CODE");
    
                throw new RpcException(
                    new Status(
                        StatusCode.Internal,
                        opEx.Message
                    )
                );
    
            }
        }
    }
    

On the TypeScript-based frontend, I simply catch RPC errors and hydrate the message like this:

JSON.parse(err.message ?? {}) as ErrorSynopsisDto
Related