2013-06-21 80 views
1

不確定bext方法如何向客戶端顯示db異常(ajax調用)?我應該在控制器波紋管中放置一個try/catch嗎?目前,我得到了我的ajax調用的通用異常?從mvc控制器顯示db異常到我的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()); 
    } 

Ajax調用:

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); 
    } 
} 

我不斷收到,而不是存儲過程內部服務器錯誤缺少(真正的例外)。

回答

0

阿賈克斯error回調函數處理http錯誤(但不是針對特定服務器錯誤)。因此它不會顯示的專用錯誤message.change你這樣的代碼:

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) 
      } 
     }   
    }); 
相關問題