开发者

What is your custom exception hierarchy?

My question is: how would you create exception hierarchy in your application?

Designing the architecture of an application, from my perspective, we could have three types of exceptions:

  • the built-in (e.g.: InvalidOperationException)
  • custom internal system faults (database transaction failed on commit, DbTransactionFai开发者_如何学运维ledException)
  • custom business exceptions (BusinessRuleViolationException)

Class hierarchy:

  • Exception
    • MyAppInternalException
      • DbTransactionFailedException
      • MyServerTimeoutException
      • ...
    • MyAppBusinessRuleViolationException
      • UsernameAlreadyExistsException
      • ...

where only MyAppInternalException & MyAppBusinessRuleViolationException would be catched.


The real benefit of exception type E inheriting from type F is apparently when E is caught by a module that doesn't specifically know what E is, but does know about F. Assuming the inheritance makes sense, the module has a reasonable hope of taking the right corrective action for an E exception, based on it being a kind of E exception.

So I tend to class exceptions according to how they can reasonably be handled. For example, a typical business process might use something like:

  • ConfigurationException -- things that can be fixed by changing a config file. E.g. config cannot be parsed or is not consistent. Appropriate response is to warn the user to fix the config (with helpful hints if possible).
  • InfrastructureException -- things that can sporadically go wrong with resources outside the program's control, like remote servers, etc. Appropriate response is often to disconnect and retry after a pause, and give up if there are too many failures.
  • DataException -- things that are wrong in incoming data. An appropriate response is to log the complaint (and possibly the data) and ignore this message.

These can be subclassed of course. But distinction at that level is often more useful to modules closer to the source of the exception. If an exception bubbles all the way to main module then there are usually only a few possible actions, and it easiest to have a one-to-one correspondence between those actions and the catch statements they respond to.


"UsernameAlreadyExistsException"

I think you shouldn't use an exception to control regular flow of your application. i.e. This is a regular business case and shouldn't appear as an exception. There is no MyAppBusinessRuleViolationException in a correct application design.

Regards,

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜