如何向客户端报告模型状态和应用程序错误的推荐方法?

3
我想知道在向浏览器报告应用程序或模型状态错误方面的最佳实践是什么,这些错误将显示给用户。您可以抛出异常并在jquery post的错误处理程序中处理它吗?例如,考虑以下方法:
[HandlerErrorWithAjaxFilter, HttpPost]
        public ActionResult RetrievePassword(string email)
        {
            User user = _userRepository.GetByEmail(email);

            if (user == null)
                throw new ClientException("The email you entered does not exist in our system.  Please enter the email address you used to sign up.");

            string randomString = SecurityHelper.GenerateRandomString();
            user.Password = SecurityHelper.GetMD5Bytes(randomString);
            _userRepository.Save();

            EmailHelper.SendPasswordByEmail(randomString);

            if (Request.IsAjaxRequest())
                return Json(new JsonAuth { Success = true, Message = "Your password was reset successfully. We've emailed you your new password.", ReturnUrl = "/Home/" });
            else
                return View();           
        }

当用户为null时,抛出异常是否正确?还是我应该这样做,并在jquery post的成功处理程序中处理它:

return Json(new JsonAuth { Success = false, Message = "The email you entered does not exist in our system.  Please enter the email address you used to sign up.", ReturnUrl = "/Home/" });
1个回答

5
不要通过抛出异常来处理验证。如果您正在发送JSON响应,请在JSON响应中包含客户端所需的所有内容:
return Json(new JsonAuth { 
    Success = false, 
    Message = "The email you entered does not exist in our system.  Please enter the email address you used to sign up.", 
    ReturnUrl = "/Home/" 
});

如果您正在返回一个视图,请添加模型状态错误,表单中的HTML助手将处理其余部分:

ModelState.AddModelError("email", "The email you entered does not exist in our system.  Please enter the email address you used to sign up.");
return View();

谢谢。你认为我的方法可能是我在这里发布的问题的原因吗:http://stackoverflow.com/questions/5171369/jquery-ajax-posts-multiple-times-one-extra-after-each-subsequent-submit - Prabhu
@Prabhu,我看到了这个问题,但是对于我来说,代码太多了,难以理解。我会从做一些简单的事情开始:没有插件和花哨的东西。一旦我让它工作起来,我就会继续改进,直到找到错误为止。 - Darin Dimitrov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接