在这种情况下,通用异常处理是否还不错? [英] Is General Exception handling not so bad in this case?

查看:92
本文介绍了在这种情况下,通用异常处理是否还不错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,我尝试发送一组通知,并且我想知道通知是否已成功发送(稍后将其放入数据库中,因此不再发送)。

In the code below I try to send a set of notifications and I want to know if a notification was sent successfully (to put it in a database later so never send it again).

难道我在这里捕获了 Exception 吗?我真的不在乎未发送通知的原因。

Is it bad I'm catching Exception here? I really don't care about the reason a notification wasn't sent.

private static async Task<List<Tuple<NotificationToSend, bool>>> SendNotificationsAsync(IEnumerable<NotificationToSend> notificationsToSend)
{
    var tuples = new List<Tuple<NotificationToSend, bool>>();

    using (var smtpClient = new SmtpClient())
    {
        foreach (var notification in notificationsToSend)
        {
            bool sentSuccessfully;

            try
            {
                var mailMessage = new MailMessage
                {
                    Subject = notification.Subject,
                    Body = $"{notification.Text} <br /> This notification was sent automatically",
                    IsBodyHtml = true
                };

                mailMessage.To.Add(notification.ToEmail);

                await smtpClient.SendMailAsync(mailMessage);
                sentSuccessfully = true;
            }
            catch (Exception e)
            {
                sentSuccessfully = false;
                // Here I also plan to log the exception
            }

            var tuple = new Tuple<NotificationToSend, bool>(notification, sentSuccessfully);
            tuples.Add(tuple);
        }
    }

    return tuples;
}


推荐答案

取决于您想要的行为实现。
这样的Blanket catch会使程序瘫痪,即使有人在try ... catch内引入了诸如空引用之类的钝错误。通常这是不希望的,最好是快速失败。

Depends what behavior you want to achieve. Blanket catch like this will make program "limp" even if someone introduces a blunt error like null reference inside try...catch. Usually this is not desired and it's better to fail fast.

如果您希望程序仅在预期的 SMTP基础结构错误之后继续进行,则仅捕获特定类型的异常(例如SmtpException或SendMailAsync可以抛出的任何东西),否则让异常冒泡。

If you want program to carry on only after 'expected' SMTP infrastructural error then catch only specific types of exceptions (e.g. SmtpException or whatever can be thrown by SendMailAsync) and otherwise let the exception to bubble up.

这篇关于在这种情况下,通用异常处理是否还不错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆