user140503 user140503 - 2 months ago 19
ASP.NET (C#) Question

Catch exception in contact form

I'm going to create form contact in asp.net mvc 4. I have yet form in html and code in controller. And his looks like:

[HttpPost]
public ActionResult Kontakt(KontaktModel k)
{
if (ModelState.IsValid)
{
try
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
MailAddress from = new MailAddress(k.Mail.ToString());
StringBuilder sb = new StringBuilder();
msg.To.Add("myemail@gmail.com");
msg.Subject = k.Temat.ToString();
msg.IsBodyHtml = false;
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
sb.Append("Nick / Imię i nazwisko: " + k.Name);
sb.Append(Environment.NewLine);
sb.Append("Typ problemu: " + k.TypProblemu);
sb.Append(Environment.NewLine);
sb.Append("Treść:");
sb.Append(Environment.NewLine);
sb.Append(k.Tresc);
msg.Body = sb.ToString();
smtp.Send(msg);
msg.Dispose();
return View("SUCCESS");
}
catch(Exception)
{
return View("Error");
}
}
return View();
}


}


But when I clicked to button app return Error.cshtml. I have a question, how I can know how exception catched? I don't know why it does not work. Any ideas?

Answer

The answer should be to get the Exception Message and put inside a ViewBag.Message and show it in the Error.cshtml view.

Error:

@ViewBag.Message

But is good to know little more about Exception and Exception Handling. If you only declare a try catch and a exception happen it will go inside the catch is the same if you do try catch(Exception) if you want to know more detail about the exception is happening you can declare a variable, example :

try{
   ///code
 }catch(Exception e){}

and then you can watch inside the variable for more detail.

The good practice is to know what type of exception you can receive and handle, here is a link that have a good explanation Exception and Exception Handling

Example:

try
{
 //code
}
catch(Exception c)
{
  ViewBag.Message = c.Message
  return View("ERROR");
}