开发者

What's the recommended way to report model state and application errors to client?

I'm wondering what the b开发者_运维知识库est practice is in reporting back to the browser about application or model state errors that would be displayed to the user. Can you throw an exception and handle it in the error handler of the jquery post? For example, consider this method:

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

Is it correct to throw an exception in this case when the user is null? Or should I instead do this and handle it in the success handler of the 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/" });


Don't handle validation by throwing exceptions. If you are sending a JSON response include all that's needed to the client in the JSON response:

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

and if you are returning a view add a model state error and the HTML helpers on your form will do the rest:

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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜