簡體   English   中英

使用MediatR時,Dapper的DataException消失了

[英]DataException from Dapper disappear when using 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帶有錯誤描述,而不是沒有內容

這是引發的異常:

在此處輸入圖片說明


如果我將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無法按預期工作?

MediatR的預處理器在AggregateExceptionAggregateException管道中的所有異常。

您必須公開它-例如帶有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
        };
        //....

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM