1

不确定向客户端显示异常(如 db 异常)的最佳方法(ajax 调用)?我应该在下面的控制器中放置一个 try/catch 吗?目前,我的 ajax 调用有一个通用异常?

控制器:

// GET: Agency Grants 
    public JsonResult GetAgencyGrants(int agencyID)
    {
        AuditDAL ad = new AuditDAL();
        var grants = ad.GetAgencyGrants(agencyID); //exception here
        return this.Json(grants.ToList());
    } 

阿贾克斯调用:

function GetAuditTypes(container) {
    $.ajax({
        url: '/AMS/Audit/GetAuditTypes',
        type: 'post',
        success: function (result) {
            $.each(result, function (i, item) {
                container.append($('<option/>').text(result[i].Audit_Type_Desc).attr('value', result[i].Audit_Type_ID));
            });
        },
        error: function (xhr, err) {
            alert("GetAuditTypes not returned: " + formatErrorMessage(xhr, err)); 
        }
    });
}

格式化功能:

// formats errors returned
function formatErrorMessage(jqXHR, exception) {

    if (jqXHR.status === 0) {
        return ('Not connected.\nPlease verify your network connection.');
    } else if (jqXHR.status == 404) {
        return ('The requested page not found. [404]');
    } else if (jqXHR.status == 500) {
        return ('Internal Server Error [500].');
    } else if (exception === 'parsererror') {
        return ('Requested JSON parse failed.');
    } else if (exception === 'timeout') {
        return ('Time out error.');
    } else if (exception === 'abort') {
        return ('Ajax request aborted.');
    } else {
        return ('Uncaught Error.\n' + jqXHR.responseText);
    }
}

我不断收到内部服务器错误,而不是缺少存储的过程(真正的例外)。

4

1 回答 1

0

ajaxerror回调函数处理http错误(但不是特定的服务器错误)。因此它不会显示专门的错误消息。像这样更改您的代码:

  public JsonResult GetAgencyGrants(int agencyID)
    {
        AuditDAL ad = new AuditDAL();
        try
        {
           var grants = ad.GetAgencyGrants(agencyID); //exception here
           return this.Json(grants.ToList());
        }
        catch(Exception e){
            return this.Json(e.Message); 
        }             
    } 

并将您的 javascript 代码更改为:

$.ajax({
        url: '/AMS/Audit/GetAuditTypes',
        type: 'post',
        success: function (result) {
            if (result instanceof Array)
            {
            $.each(result, function (i, item) {
                container.append($('<option/>').text(result[i].Audit_Type_Desc).attr('value', result[i].Audit_Type_ID));
            });
             }
             else{
                // Exception Occurred 
                // do somethings with result(contains error message)
             }
        }           
    });
于 2013-06-21T14:45:53.433 回答