如何:处理异常,最佳实践 [英] how to: handle exceptions, best practices

查看:79
本文介绍了如何:处理异常,最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要实现一个全球性的错误处理,所以也许你可以帮忙通过下面的例子...

我有这个code:

 公共BOOL IsUserAuthorizedToSignIn(字符串userEMailAddress,字符串的userPassword)
        {
            //获取MD5哈希在LINQ查询使用
            字符串passwordSaltedHash = this.PasswordSaltedHash(userEMailAddress,userPassword的);            //检查电子邮件/密码/有效期
            使用(UserManagementDataContext上下文=新UserManagementDataContext())
            {
                VAR用户从u在context.Users =
                            其中,u.UserEMailAdresses.Any(E => e.EMailAddress == userEMailAddress)
                                &功放;&安培; u.UserPasswords.Any(P => p.PasswordSaltedHash == passwordSaltedHash)
                                &功放;&安培; u.IsActive ==真
                            选择U;                // true,如果用户发现
                返回(users.Count()== 1)?真假;
            }
        }

和的MD5还有:

 私人字符串PasswordSaltedHash(字符串userEMailAddress,字符串的userPassword)
        {
            MD5散列器= MD5.Create();
            字节[]数据= hasher.ComputeHash(Encoding.Default.GetBytes(userPassword的+ userEMailAddress));            StringBuilder的StringBuilder的=新的StringBuilder();
            的for(int i = 0; I< data.Length;我++)
            {
                stringBuilder.Append(数据[I]的ToString(×2));
            }            Trace.WriteLine(的String.Empty);
            Trace.WriteLine(散列:+ stringBuilder.ToString());
            返回stringBuilder.ToString();
        }

所以,我怎么会去了解这些功能的处理异常?他们第一个是从Default.aspx页面调用。第二个是只从类库等功能调用。

什么是最好的做法是什么?


  • 环绕code内的每个功能的的try-catch

  • 与周围函数调用的try-catch

  • 别的东西??

如果发生异常怎么办?

在这个例子:
这是一个用户登录,所以不知何故,即使这些都失败,用户应该得到一些有意义的信息 - 大意:在不正常的不可能登录OK(只是重定向),符号(错误的用户名/密码),标志由于内部问题,不好意思(例外发生过)。

有第一函数我担心如果没有与数据库访问的问题。
不知道是否有任何需要在第二个进行处理。

日Thnx的信息。你会怎么做呢?
需要在这个特定的信息(我更容易理解),而且一般的信息如何处理其它任务/功能。

我看了看周围的互联网,但每个人都有不同的话要说,所以不确定该怎么办...将在这里无论是得票最多去,或者最logicaly解释的答案:)谢谢你。


解决方案

  

您库code或code是
  使用更高层的
  应用程序必须始终只能扔
  例外,从不担心如何
  对付他们。


这是重要的,因为你可以在很多地方为了不同的目的使用这个库。

在您的应用程序presentation层,如果你消耗库code和你意识到对可能的例外那么就赶上他们的try / catch。

由于您使用asp.net我建议写一个普通页面的基类和工作在 Page_Error事件事件的一些错误处理机制,捕获所有非在页面上处理的异常。

甚至超越,你可以使用的Application_Error 甚至在Global.asax中捕捉任何未经处理的异常在应用程序的任何部分,模块,处理程序,服务,网页等


  

我强烈建议不要使它
  通常的做法来处理所有
  例外全球的Application_Error。


need to implement a global error handling, so maybe you can help out with the following example...

i have this code:

public bool IsUserAuthorizedToSignIn(string userEMailAddress, string userPassword)
        {
            // get MD5 hash for use in the LINQ query
            string passwordSaltedHash = this.PasswordSaltedHash(userEMailAddress, userPassword);

            // check for email / password / validity
            using (UserManagementDataContext context = new UserManagementDataContext())
            {
                var users = from u in context.Users
                            where u.UserEMailAdresses.Any(e => e.EMailAddress == userEMailAddress)
                                && u.UserPasswords.Any(p => p.PasswordSaltedHash == passwordSaltedHash)
                                && u.IsActive == true
                            select u;

                // true if user found
                return (users.Count() == 1) ? true : false;
            }
        }

and the md5 as well:

private string PasswordSaltedHash(string userEMailAddress, string userPassword)
        {
            MD5 hasher = MD5.Create();
            byte[] data = hasher.ComputeHash(Encoding.Default.GetBytes(userPassword + userEMailAddress));

            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                stringBuilder.Append(data[i].ToString("x2"));
            }

            Trace.WriteLine(String.Empty);
            Trace.WriteLine("hash: " + stringBuilder.ToString());
            return stringBuilder.ToString();
        }

so, how would i go about handling exceptions from these functions? they first one is called from the Default.aspx page. the second one is only called from other functions from the class library.

what is the best practice?

  • surround code INSIDE each function with try-catch
  • surround the FUNCTION CALL with try-catch
  • something else??

what to do if exceptions happen?

in this example: this is a user sign in, so somehow even if everything fails, the user should get some meaningful info - along the lines: sign in ok (just redirect), sign in not ok (wrong user name / password), sign in not possible due to internal problems, sorry (exception happened).

for the first function i am worried if there is a problem with database access. not sure if there is anything that needs to be handled in the second one.

thnx for the info. how would you do it? need specific info on this (easier for me to understand), but also general info on how to handle other tasks/functions.

i looked around the internet but everyone has different things to say, so unsure what to do... will go with either most votes here, or most logicaly explained answer :) thank you.

解决方案

Your library code or the code that is used by higher-layers in your application must always only throw exceptions and never worry about how to deal with them.

This is important because you may use this library at many places for different purposes.

In your application presentation layer, if you're consuming a library code and you're aware about the possible exceptions then do catch them with try/catch.

Since you're using asp.net I'd recommend to write a common page-base class and work some error handling mechanism in Page_Error event that catches all un-handled exceptions on the page.

Even beyond that you can use Application_Error even in global.asax to catch any un-handled exception in any part of the application, Modules, Handler, services, pages etc.

I'd strongly recommend to not make it a general practice to handle all exception in global Application_Error.

这篇关于如何:处理异常,最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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