public ApiExceptionMiddleware(ApiExceptionOptions options, RequestDelegate next,
                               ILogger <ApiExceptionMiddleware> logger)
 {
     _next    = next;
     _logger  = logger;
     _options = options;
 }
        public static IApplicationBuilder UseApiExceptionHandler(this IApplicationBuilder builder,
                                                                 Action <ApiExceptionOptions> configureOptions)
        {
            var options = new ApiExceptionOptions();

            configureOptions(options);

            return(builder.UseMiddleware <ApiExceptionMiddleware>(options));
        }
        private async Task HandleExceptionAsync(HttpContext context, Exception exception, ApiExceptionOptions apiExceptionOptions)
        {
            var errorId = Guid.NewGuid().ToString();

            // This is what we tell the client.
            var outcome = new OperationOutcome
            {
                ErrorId  = errorId,
                Errors   = Enumerable.Empty <string>(),
                IsError  = true,
                Message  = string.Format(Errors.UnhandledError, errorId),
                OpResult = OpResult.Fail
            };

            apiExceptionOptions.AddResponseDetails?.Invoke(context, exception, outcome);

            // This is what we log.
            var resolvedExceptionMessage = GetInnermostExceptionMessage(exception);

            var level = _options.DetermineLogLevel?.Invoke(exception) ?? LogLevel.Error;

            _logger.Log(level,
                        EventIDs.EventIdUncaughtGlobal,
                        exception,
                        MessageTemplates.UncaughtGlobal,
                        resolvedExceptionMessage,
                        errorId
                        );

            var apiResponse = new ApiResponse <IEnumerable <string> >
            {
                Data = Enumerable.Empty <string>(), Outcome = outcome
            };

            var result = JsonSerializer.Serialize(apiResponse, Common.JsonSerializerOptions);

            context.Response.ContentType = MediaTypeNames.Application.Json;
            context.Response.StatusCode  = (int)HttpStatusCode.InternalServerError;

            await context.Response.WriteAsync(result);
        }
Example #4
0
        private async Task HandleExceptionAsync(HttpContext context, Exception exception, ApiExceptionOptions apiExceptionOptions)
        {
            var errorId = Guid.NewGuid().ToString();

            // This is what we tell the client.
            var outcome = OperationOutcome.UnSuccessfulOutcome;

            outcome.ErrorId = errorId;

#if DEBUG
            outcome.Message = Errors.UnhandledErrorDebug.FormatAs(exception.GetBaseException().Message);
            outcome.Errors  = exception.StackTrace.Split(
                Environment.NewLine, StringSplitOptions.RemoveEmptyEntries
                ).Select(str => str.Trim()); // ease of readability, for debugging purposes 👍
#else
            outcome.Message = Errors.UnhandledError.FormatAs(errorId);
#endif


            apiExceptionOptions.AddResponseDetails?.Invoke(context, exception, outcome);

            // This is what we log.
            var resolvedExceptionMessage = GetInnermostExceptionMessage(exception);

            var level = _options.DetermineLogLevel?.Invoke(exception) ?? LogLevel.Error;

            _logger.Log(level,
                        EventIDs.EventIdUncaughtGlobal,
                        exception,
                        MessageTemplates.UncaughtGlobal,
                        resolvedExceptionMessage,
                        errorId
                        );

            var apiResponse = new ApiResponse <object>
            {
                Data    = null,
                Outcome = outcome
            };

            var result = JsonSerializer.Serialize(apiResponse, Common.JsonSerializerOptions);
            context.Response.ContentType = MediaTypeNames.Application.Json;
            context.Response.StatusCode  = StatusCodes.Status500InternalServerError;

            await context.Response.WriteAsync(result);
        }