【问题标题】:How to handle rest exceptions in CQRS?如何处理 CQRS 中的其余异常?
【发布时间】:2020-05-18 21:37:54
【问题描述】:

在我的 aspnet core 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>();

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

             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


    【解决方案1】:

    您的中间件看起来不错,但乍一看,我会说您可能是从异步代码中抛出 RestException,它可能会被包装为 AggregateException

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

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

    【讨论】:

    • 我添加了聚合,但仍然是同样的问题
    【解决方案2】:

    您的自定义中间件可能与 DeveloperExceptionPage 中间件发生冲突。你能检查一下你没有调用app.UseDeveloperExceptionPage() 方法吗?

    【讨论】:

    • 我没有使用 app.UseDeveloperExceptionPage() ,注释掉了,我正在使用生产模式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    • 1970-01-01
    • 2015-12-13
    • 2011-06-05
    相关资源
    最近更新 更多