Exception handling using an HttpModule

前端 未结 6 1467
渐次进展
渐次进展 2021-02-10 04:24

We\'re reviewing one of the company\'s system\'s exception handling and found a couple of interesting things.

Most of the code blocks (if not all of them) are inside a t

6条回答
  •  时光取名叫无心
    2021-02-10 04:54

    Never1 catch (Exception ex). Period2. There is no way you can handle all the different kinds of errors that you may catch.

    Never3 catch an Exception-derived type if you can't handle it or provide additional information (to be used by subsequent exception handlers). Displaying an error message is not the same as handling the error.

    A couple of reasons for this, from the top of my head:

    • Catching and rethrowing is expensive
    • You'll end up losing the stack trace
    • You'll have a low signal-to-noice ratio in your code

    If you know how to handle a specific exception (and reset the application to pre-error state), catch it. (That's why it's called exception handling.)

    To handle exceptions that are not caught, listen for the appropriate events. When doing WinForms, you'll need to listen for System.AppDomain.CurrentDomain.UnhandledException, and - if your doing Threading - System.Windows.Forms.Application.ThreadException. For web apps, there are similar mechanisms (System.Web.HttpApplication.Error).

    As for wrapping framework exceptions in your application (non-)specific exceptions (i.e. throw new MyBaseException(ex);): Utterly pointless, and a bad smell.4


    Edit

    1 Never is a very harsh word, especially when it comes to engineering, as @Chris pointed out in the comments. I'll admit to being high on principles when I first wrote this answer.

    2,3 See 1.

    4 If you don't bring anything new to the table, I still stand by this. If you have caught Exception ex as part of a method that you know could fail in any number of ways, I believe that the current method should reflect that in it's signature. And as you know, exceptions is not part of the method signature.

提交回复
热议问题