简体   繁体   English

使抛出异常起作用

[英]Making throwing exceptions work

I've been trying to write a small program with these instructions: 我一直在尝试按照以下说明编写一个小程序:

In this assignment you should write a simple web application with one link on the front page of the web. 在此作业中,您应该编写一个简单的Web应用程序,并在Web主页上提供一个链接。 If the link is clicked, the user will simply be routed to the front page again (using RedirectToAction ). 如果单击链接,则仅将用户再次路由到首页(使用RedirectToAction )。 However, occasionally, the action method might throw an exception (but not always). 但是,有时,操作方法可能会引发异常(但并非总是如此)。 Occasionally (one in every 5 occasions) the method should throw an ArgumentException , and occasionally (again, in maybe 1 in a 5), it should throw a custom Exception object you should declare yourself, called MyApplicationException. 有时(每5次出现一次)该方法应引发ArgumentException ,有时(再次,可能是5分之一),应引发一个自定义Exception对象,您应声明自己,称为MyApplicationException。

In HomeController I have: HomeController中,我有:

public class HomeController : Controller
{
    List<Logger> m_loggers = new List<Logger>();

    protected override void OnException(ExceptionContext fc)
    {
        base.OnException(fc);
        Exception ex = fc.Exception;

        Logger.Instance.Log(ex);
    }

    public ActionResult Index()
    {
        string strLogFile = System.Configuration.ConfigurationManager.AppSettings["LogFile"];
        string strEmail = System.Configuration.ConfigurationManager.AppSettings["Email"];

        try
        {
            RedirectToAction("Index");

            using(MailMessage message = new MailMessage())
            {
                message.To.Add(strEmail);
                message.Subject = "Villuskilaboð";
                message.Body = "Upp hefur komið villa frá Skilaverkefni 4!";

                using(SmtpClient client = new SmtpClient())
                {
                    client.EnableSsl = true;
                    client.Send(message);
                }
            }
        }
        catch(Exception ex)
        {
            Random r = new Random();
            int rand = r.Next(1000);

            if(rand % 5 == 0)
            {
                throw new System.ArgumentException("Randon villuskilaboð handa þér!");
            }

            Debug.WriteLine(ex.Message +
                            Environment.NewLine +
                            ex.StackTrace);
        }

        return View();
    }

Logger class: Logger类:

public class Logger
{
    List<LogMedia>m_loggers = new List<LogMedia>();

    private static Logger theInstance = null;

    public static Logger Instance
    {
        get
        {
            if (theInstance == null)
            {
                theInstance = new Logger();
            }
            return theInstance;
        }
    }

    private Logger()
    {
        m_loggers = new List<LogMedia>();
        //m_loggers.Add(new TextFileLogMedia { });
        //m_loggers.Add(new EmailLogMedia { });
    }

   public void Log(Exception ex)
   {
       foreach(LogMedia log in m_loggers)
       {
           log.LogMessage(ex.Message + Environment.NewLine);
       }
    }
}

LogMedia

public class LogMedia
{
    public virtual void LogMessage(string Message)
    {
    }

    public class OutputWindowLogMedia: LogMedia
    {
        public override void LogMessage(string Message)
        {
            System.Diagnostics.Debug.WriteLine(Message);
        }
    }

    public class TextFileLogMedia: LogMedia
    {
        public override void LogMessage(string Message)
        {
            //File.AppendAllText("c:\\Temp.Log.txt", Message);
        }
    }

    public class EmailLogMedia: LogMedia
    {
        public override void LogMessage(string Message)
        {
        }
    }
}

I´m stuck for now and seems not getting it to work, my Visual Studio crash and I get error up, don't think that is the exception, I´m so new to it so maybe it´s the box that should come up :) But the email never get to my account. 我暂时停滞不前,似乎无法正常工作,Visual Studio崩溃了并且出现了错误,不要以为是例外,我是个新手,所以也许这应该是盒子up :)但是电子邮件从未进入我的帐户。

What am I still missing to make everything work? 使一切正常工作我还缺少什么? I know the file-thing isn't in this code, trying to make the other things to work first. 我知道文件中没有此代码,因此尝试使其他功能首先生效。

I've added information about my eMail in web.config . 我在web.config添加了有关我的电子邮件的信息。

You really need to rework your Index() method. 您确实需要重新处理Index()方法。 I'm not in front of my computer with Visual Studio, but I'm surprised you code gets past the first line in your try . 我不在使用Visual Studio的计算机前,但是令您惊讶的是代码超出了try的第一行。 Having the RedirectToAction("Index") should throw a warning that the rest of the method will never be reached, and create an infinite loop when you try to access the method. 拥有RedirectToAction("Index")应该会发出一条警告,即该方法的其余部分将永远无法到达,并在尝试访问该方法时创建一个无限循环。 The RedirectToAction("Index")` you have in your code does nothing as you don't return the results of that. 您的代码中的RedirectToAction(“ Index”)`不会执行任何操作,因为您不会返回结果。 Thank you Erik Noren 谢谢你Erik Noren

This would be how I'd structure your method instead: 这将是我构造您的方法的方式:

public ActionResult Index() {
    // No need to go higher, as it's always just as random with a modulo
    int rnd = (new Random()).Next(5); 

    try {
        switch (rnd) {
            case 1: // Or any of the 5 numbers you want.
                throw new ArgumentException();
            case 4: // Again, any of the 5 numbers
                throw new MyApplicationException();
            default:
                return RedirectToAction("Index");
        }
    }
    catch (Exception ex) {
        // Do your error logging here.
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM