使用MediatR时,Dapper的DataException消失

时间:2017-08-01 08:08:56

标签: c# error-handling asp.net-core dapper mediatr

我遇到一个奇怪的问题,来自Dapper的DataExceptions没有正确地进行推断。

这是我的设置:

public class CustomerController : Controller
{
    private readonly IMediator _mediator;

    public CustomerController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpGet]
    public async Task<IActionResult> Get(Get.Query query)
    {
        var result = await _mediator.Send(query);
        return Ok(result);
    }
}

public class Get
{
    public class Query : IRequest<IEnumerable<Result>>
    {
    }

    public class Result
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
    }

    public class QueryHandler : IAsyncRequestHandler<Query, IEnumerable<Result>>
    {
        private readonly IDbConnection _dapper;

        public QueryHandler(IDbConnection dapper)
        {
            _dapper = dapper;
        }

        public async Task<IEnumerable<Result>> Handle(Query message)
        {
            // the below throws because of incorrect type mapping
            // (yes, the connection is open)
            var customers =
                await _dapper.Connection.QueryAsync<Result>("SELECT Id, Name FROM [Customer].[Customers]");
            return customers;
        }
    }
}

结果

  

卷曲
  curl -X GET'http://localhost:5000/api/Customer'
  请求网址
  http://localhost/api/Customer
  响应主体
  没有内容
  响应代码
  500

预期

我预计会有500个错误说明,而不是没有内容

这是抛出的异常:

enter image description here

如果我将Handle方法更改为:

public async Task<IEnumerable<Result>> Handle(Query message)
{
    throw new DataException("What is going on?");
}

我得到了预期的结果。一个500,错误地说“发生了什么事?”

因为我启用了app.UseDeveloperExceptionPage();,所以看起来像这样。

An unhandled exception occurred while processing the request.

DataException: What is going on? 
...Customer.Get+QueryHandler+<Handle>d__2.MoveNext() in Get.cs, line 42

Stack Query Cookies Headers 
DataException: What is going on? 
...

但这是预期的。

那是怎么回事?为什么Dapper的DataException没有按预期工作?

1 个答案:

答案 0 :(得分:0)

MediatR的预处理器将AggregateException中管道中的所有异常汇总。

您必须公开它-例如使用ExceptionFilterAttribute

public class MyExceptionFilterAttribute : ExceptionFilterAttribute
{
    public override void OnException(HttpActionExecutedContext context)
    {
        Exception exception = context.Exception;

        if (exception is AggregateException
            && exception.InnerException != null)
        {
            exception = exception.InnerException;
        }
        // check type and do you stuff ........
        context.Response = new HttpResponseMessage
        {
            Content = this.CreateContent(response),
            StatusCode = HttpStatusCode.BadRequest
        };
        //....