コード例 #1
0
        private Action <IApplicationBuilder> CustomExceptionHandlerMiddleware(IServiceScopeFactory serviceScopeFactory, bool isDevelopment)
        {
            return(applicationBuilder => applicationBuilder.Run(async httpContext =>
            {
                var exceptionHandlerPathFeature = httpContext.Features.Get <IExceptionHandlerPathFeature>();
                Exception specificException = exceptionHandlerPathFeature.Error;
                _logger.LogError("Api Unhandle Exception: {0}", JsonConvert.SerializeObject(specificException));

                using (var scope = serviceScopeFactory.CreateScope())
                {
                    ICachingService cachingService = scope.ServiceProvider.GetService <ICachingService>();
                    ITransactionLogService transactionLogService = scope.ServiceProvider.GetService <ITransactionLogService>();

                    if (await cachingService.IsLoggingDatabaseAsync())
                    {
                        await transactionLogService.AddTransactionLogAsync(TransactionLogStep.CustomExceptionHandlerMiddleware, TransactionLogStatus.Error, JsonConvert.SerializeObject(specificException), string.Empty, specificException.Message, specificException.StackTrace);
                    }
                }

                var code = HttpStatusCode.InternalServerError;
                var responseObject = new BaseResponseObject
                {
                    Status = false,
                    ErrorCode = ResponseErrorCode.UnhandleException,
                    Message = specificException.Message,
                    StackTrace = isDevelopment ? specificException.StackTrace : string.Empty,
                    Data = specificException.Data
                };

                switch (specificException)
                {
                case ArgumentNullException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.ArgumentNullException;
                    break;

                case ArgumentOutOfRangeException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.ArgumentOutOfRangeException;
                    break;

                case ArgumentException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.ArgumentException;
                    break;

                case NotFoundException _:
                    code = HttpStatusCode.NotFound;
                    responseObject.ErrorCode = ResponseErrorCode.NotFound;
                    break;

                case InvalidOperationException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.InvalidOperationException;
                    break;

                case AuthenticationException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.AuthenticationException;
                    break;
                }

                var result = JsonConvert.SerializeObject(responseObject);
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.StatusCode = (int)code;

                await httpContext.Response.WriteAsync(result);
            }
                                                                ));
        }
        public async Task Invoke(HttpContext httpContext)
        {
            string requestData = string.Empty;

            try
            {
                requestData = await GetRequestData(httpContext);
            }
            catch (Exception ex)
            {
                _logger.LogError($"Api Unhandle Exception: {nameof(GetRequestData)}", JsonConvert.SerializeObject(ex));
            }

            try
            {
                await _next(httpContext);
            }
            catch (Exception ex)
            {
                _logger.LogError("Api Unhandle Exception", JsonConvert.SerializeObject(ex));

                using (var scope = _serviceScopeFactory.CreateScope())
                {
                    ICachingWorkerService  cachingService        = scope.ServiceProvider.GetService <ICachingWorkerService>();
                    ITransactionLogService transactionLogService = scope.ServiceProvider.GetService <ITransactionLogService>();

                    if (cachingService.IsLoggingDatabase())
                    {
                        await transactionLogService.AddTransactionLogAsync(TransactionLogStep.CustomExceptionHandlerMiddleware, TransactionLogStatus.Error, requestData, ex.Message, JsonConvert.SerializeObject(ex), Guid.Empty);
                    }
                }

                var code           = HttpStatusCode.InternalServerError;
                var responseObject = new BaseResponseObject
                {
                    Status     = false,
                    ErrorCode  = ResponseErrorCode.UnhandleException,
                    Message    = ex.Message,
                    StackTrace = !_settings.IsProduction ? ex.StackTrace : string.Empty,
                    Data       = ex.Data
                };

                switch (ex)
                {
                case ArgumentNullException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.ArgumentNullException;
                    break;

                case ArgumentOutOfRangeException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.ArgumentOutOfRangeException;
                    break;

                case ArgumentException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.ArgumentException;
                    break;

                case NotFoundException _:
                    code = HttpStatusCode.NotFound;
                    responseObject.ErrorCode = ResponseErrorCode.NotFound;
                    break;

                case InvalidOperationException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.InvalidOperationException;
                    break;

                case AuthenticationException _:
                    code = HttpStatusCode.BadRequest;
                    responseObject.ErrorCode = ResponseErrorCode.AuthenticationException;
                    break;
                }

                var result = JsonConvert.SerializeObject(responseObject);
                httpContext.Response.ContentType = "application/json";
                httpContext.Response.StatusCode  = (int)code;

                await httpContext.Response.WriteAsync(result);
            }
        }