繁体   English   中英

使抛出异常起作用

[英]Making throwing exceptions work

我一直在尝试按照以下说明编写一个小程序:

在此作业中,您应该编写一个简单的Web应用程序,并在Web主页上提供一个链接。 如果单击链接,则仅将用户再次路由到首页(使用RedirectToAction )。 但是,有时,操作方法可能会引发异常(但并非总是如此)。 有时(每5次出现一次)该方法应引发ArgumentException ,有时(再次,可能是5分之一),应引发一个自定义Exception对象,您应声明自己,称为MyApplicationException。

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类:

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)
        {
        }
    }
}

我暂时停滞不前,似乎无法正常工作,Visual Studio崩溃了并且出现了错误,不要以为是例外,我是个新手,所以也许这应该是盒子up :)但是电子邮件从未进入我的帐户。

使一切正常工作我还缺少什么? 我知道文件中没有此代码,因此尝试使其他功能首先生效。

我在web.config添加了有关我的电子邮件的信息。

您确实需要重新处理Index()方法。 我不在使用Visual Studio的计算机前,但是令您惊讶的是代码超出了try的第一行。 拥有RedirectToAction("Index")应该会发出一条警告,即该方法的其余部分将永远无法到达,并在尝试访问该方法时创建一个无限循环。 您的代码中的RedirectToAction(“ Index”)`不会执行任何操作,因为您不会返回结果。 谢谢你Erik Noren

这将是我构造您的方法的方式:

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