2014-02-10 42 views
22

MVC App,客戶端向服務器發出請求,發生錯誤,想要將msg發送回客戶端。 嘗試了HttpStatusCodeResult,但只是返回一個404沒有消息,我需要將錯誤的詳細信息發送回客戶端。返回帶動作的錯誤消息結果

public ActionResult GetPLUAndDeptInfo(string authCode) 
{ 
    try 
    { 
     //code everything works fine 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
     return new HttpStatusCodeResult(404, "Error in cloud - GetPLUInfo" + ex.Message); 
    } 
} 

回答

15

您需要返回它有一個友好的錯誤信息給用戶

catch (Exception ex) 
{ 
    // to do :log error 
    return View("Error"); 
} 

你不應該展示你的異常(如異常堆棧跟蹤等)用戶的內部細節視圖。您應該將相關信息記錄到錯誤日誌中,以便您可以通過它並修復問題。

如果您的請求是一個Ajax請求,您可能會返回一個合適的狀態標誌的JSON響應它。如果你想顯示在提交表單的用戶錯誤客戶端可以評估,並做進一步的行動

[HttpPost] 
public ActionResult Create(CustomerVM model) 
{ 
    try 
    { 
    //save customer 
    return Json(new { status="success",message="customer created"}); 
    } 
    catch(Exception ex) 
    { 
    //to do: log error 
    return Json(new { status="error",message="error creating customer"}); 
    } 
} 

,您可以使用ModelState.AddModelError方法以及Html幫助程序方法(如Html.ValidationSummary等)以用戶提交的形式向用戶顯示錯誤。

19

一種方法是隻使用ModelState

ModelState.AddModelError("", "Error in cloud - GetPLUInfo" + ex.Message); 

,然後在視圖上做這樣的事情:

@Html.ValidationSummary() 

要將錯誤顯示。如果沒有錯誤,則不會顯示,但是如果有,您會得到一個列出所有錯誤的部分。

4

在視圖中插入

@Html.ValidationMessage("Error") 

然後在控制器在模型中

var model = new yourmodel(); 
try{ 
[...] 
}catch(Exception ex){ 
ModelState.AddModelError("Error", ex.Message); 
return View(model); 
} 
4

內部控制器操作,您可以訪問HttpContext.Response使用新後。您可以在下面的列表中設置響應狀態。

[HttpPost] 
public ActionResult PostViaAjax() 
{ 
    var body = Request.BinaryRead(Request.TotalBytes); 

    var result = Content(JsonError(new Dictionary<string, string>() 
    { 
     {"err", "Some error!"} 
    }), "application/json; charset=utf-8"); 
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; 
    return result; 
} 
+2

你從哪裏得到JsonError? –

+0

@EhsanZargarErshadi:我想我找到了它:https://docs.microsoft.com/en-us/uwp/api/windows.data.json.jsonerror – Matt

+0

感謝這一行HttpContext.Response.StatusCode =(int)HttpStatusCode 。錯誤的請求; –