【发布时间】: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