如何处理CQRS中的休息异常?

问题描述 投票:0回答:2

在我的aspnet核心3.1项目中,我正在使用CQRS方法,但是我遇到了获取正确的Rest异常的问题。我会返回服务器错误,而不是实际的错误。

我的RestException类看起来像:

    public class RestException : Exception
    {
        public HttpStatusCode Code { get; }
        public object Errors { get; }

        public RestException(HttpStatusCode code, object errors = null)
        {
            Code = code;
            Errors = errors;
        }
    }

我的休息中间件:

    public class ErrorHandlingMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ErrorHandlingMiddleware> _logger;

        public ErrorHandlingMiddleware(RequestDelegate next, 
         ILogger<ErrorHandlingMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex, _logger);
            }
        }

        private async Task HandleExceptionAsync(HttpContext context, Exception exception, 
        ILogger<ErrorHandlingMiddleware> logger)
        {
            object errors = null;
            switch (exception)
            {
                case RestException re:
                    logger.LogError(exception, "REST ERROR");
                    errors = re.Errors;
                    context.Response.StatusCode = (int) re.Code;
                    break;
                case { } e:
                    logger.LogError(exception, "SERVER ERROR");
                    errors = string.IsNullOrWhiteSpace(e.Message) ? "Error" : e.Message;
                    context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
                    break;
            }

            context.Response.ContentType = "application/json";
            if (errors != null)
            {
                var result = JsonConvert.SerializeObject(new
                {
                    errors
                });
                await context.Response.WriteAsync(result);
            }
        }
    }

启动类:

 app.UseMiddleware<ErrorHandlingMiddleware>();

创建我正在使用rest异常的处理程序:

             public async Task<Project> Handle(Command request, CancellationToken 
             cancellationToken)
            {
                var project = new Project
                {
                    Name = request.Name,
                    KubesprayCurrentVersion = request.KubesprayCurrentVersion,
                    KubesprayTargetVersion = request.KubesprayCurrentVersion,
                    OrganizationId = request.OrganizationId,
                    CloudCredentialId = request.CloudCredentialId,
                    CreatedAt = DateTime.Now
                };

                await _context.Projects.AddAsync(project, cancellationToken);

                if(await _context.Projects.Where(x => x.Name == 
                 request.Name).AnyAsync(cancellationToken: cancellationToken))
                    throw new RestException(HttpStatusCode.BadRequest, new {Name = "Project 
                Name already exists"});

                var success = await _context.SaveChangesAsync(cancellationToken) > 0;
                if(success) return project;

                throw new Exception("Problem saving changes");
            }

我的项目负责人:

    [HttpPost]
    public async Task<ActionResult<Project>> Create(Create.Command command) => await 
    Mediator.Send(command);
c# asp.net-core exception middleware cqrs
2个回答
0
投票

您的中间件看起来还不错,但是乍看之下我想说的是,您可能是从异步代码中抛出了RestException,并且可能被包装为AggregateException

然后在您的HandleExceptionAsync中将不会进入RestException的情况,因此您将收到“服务器错误”消息。

您能为AggregateException添加一个案例,看看您的例外情况是否针对该案例?


0
投票

您的自定义中间件可能与DeveloperExceptionPage中间件冲突。您可以检查是否不调用app.UseDeveloperExceptionPage()方法吗?

© www.soinside.com 2019 - 2024. All rights reserved.