如何获得InsertAsync的正确响应代码?

时间:2017-09-04 07:22:13

标签: aspnetboilerplate

我有一个CreateClassification API,用于将数据插入数据库表。表中有唯一约束,因此,如果我尝试插入相同的记录,则会给出以下响应。

{
"result": null,
"targetUrl": null,
"success": false,
"error": {
"code": 0,
"message": "An internal error occurred during your request!",
"details": null,
"validationErrors": null
},
"unAuthorizedRequest": false,
"__abp": true
}

API:

await _classificationrepository.InsertAsync(classobj);

但是这个响应消息并不清楚失败原因,因为插入失败可能有很多原因,所以有没有办法找到失败的正当理由。

Msg 2627, Level 14, State 1, Line 1
Violation of UNIQUE KEY constraint 'IX_ClassificationCode'. Cannot insert duplicate key in object 'dbo.Classification'. The duplicate key value is (02).
The statement has been terminated.

正如所建议的,我已尝试过这一点,但它对api响应没有影响:

Task Createxyz(XyzInput input);

public async Task Createxyz(XyzInput input)
    {
        try
        {
            await _xyzrepository.InsertAsync(classobj);
        }
        catch (Exception)
        {

            throw new UserFriendlyException("hello");
        }
    }

点击以下网址:

http://localhost:22742/api/services/app/xyz/Createxyz

我还有一个疑问,我的Createxyz如何转换为api?,表示abp如何提供到Createxyz方法的路由,以便最终用户可以调用此api

2 个答案:

答案 0 :(得分:1)

您可以使用 IUnitOfWorkManager 。 看看下面的代码;

 public class MySampleAppService : ApplicationService
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;

        public MySampleAppService(IUnitOfWorkManager unitOfWorkManager)
        {
            _unitOfWorkManager = unitOfWorkManager;
        }

        public async Task Createxyz(XyzInput input)
        {
            try
            {
                using (var unitOfWork = _unitOfWorkManager.Begin())
                {
                    await _xyzrepository.InsertAsync(classobj);
                    unitOfWork.Complete();
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException("hello this is the exception message: " + ex.Message);
                //note: check if there's inner exceptions you need to flatten all the inner exceptions !
            }
        }
    }

答案 1 :(得分:0)

ABP隐藏了用户的异常详细信息。例如,这不是向用户显示的良好错误消息(因为用户体验和应用程序的安全性):

function addCartao(product_id){ $j('#cartaoMensagem'+product_id).hide(); $j('#cartaoMensagemRemover'+product_id).show(); $j('#cartaoMensagemRemover'+product_id).css({'background-color': '#000000'}); $j.ajax({ type: "POST", url: "<?php echo Mage::getUrl('fol_carousel/ajax/addCartao') ?>", data: { product_id: product_id }, dataType: 'json', cache : false, beforeSend: function () { }, success: function (retorno) { var button = $j('#cartaoMensagemRemover'+product_id); $j('#cartao').find(':button').not(button).attr('disabled',true); $j('.item-custom').append('<tr id="trAppend"><td class="a-center lc-thumbnails"><img src="' + retorno['imagem'] + '" width="50" height="50" alt="' + retorno['name'] + '"></td><td><h3 class="product-name">' + retorno['name'] + '</h3></td><td class="a-center">1</td><td class="a-right"><span class="cart-price"><span class="price"> R$ ' + retorno['price'] + '</span></span></td></tr>'); getSubTotal(); getGrandTotal(); }, complete: function () { }, error: function (x,y,z) { alert("error"); alert(x); alert(y); alert(z); window.location.reload(); history.go(0); window.location.href=window.location.href; } }); } function removeCartaotoCart(itemId){ $j('#cartaoMensagemRemover'+itemId).hide(); $j('#cartaoMensagem'+itemId).show(); $j.ajax({ type:"POST", url:"<?php echo Mage::getUrl('fol_carousel/ajax/removeCartao') ?>", data:{ itemId: itemId }, cache: false, beforeSend: function(){ }, success: function(retorno){ var button = $j('#cartaoMensagemRemover'+itemId); $j('#cartao').find(':button').attr('disabled',false); $j('.item-custom #trAppend').remove(); getSubTotal(); getGrandTotal(); }, complete: function () { }, error: function (x,y,z) { alert("error"); alert(x); alert(y); alert(z); window.location.reload(); history.go(0); window.location.href=window.location.href; } }); }

因此,您应该自己处理特定类型的异常(我不知道您的情况下的异常类型)并自己抛出Violation of UNIQUE KEY constraint 'IX_ClassificationCode'. Cannot insert duplicate key in object 'dbo.Classification'. The duplicate key value is (02).

UserFriendlyException是一种特定类型的异常,因此ABP直接向最终用户显示异常消息。

修改

示例:

UserFriendlyException

我不知道是否存在这样的SqlDuplicateKeyException。要了解它的类型,请捕获常规异常并检查它的类型或消息。这是基本的C#练习。