How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP?

后端 未结 3 1527
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 01:17

I\'m currently writing an ASP.Net app from the UI down. I\'m implementing an MVP architecture because I\'m sick of Winforms and wanted something that had a better separation

3条回答
  •  醉话见心
    2020-12-13 02:01

    That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notification of the problem.

    Don't catch Exception

    However, don't catch Exception in the presenter, I know its tempting because it keeps the code shorter, but you need to catch specific exceptions to avoid catching the system-level exceptions.

    Plan a Simple Exception Hierarchy

    If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes. At a minumum create a ServiceLayerException class and throw one of these in your service methods when a problem occurs. Then if you need to throw an exception that should/could be handled differently by the presenter, you can throw a specific subclass of ServiceLayerException: say, AccountAlreadyExistsException.

    Your presenter then has the option of doing

    try {
      // call service etc.
      // handle success to view
    } 
    catch (AccountAlreadyExistsException) {
      // set the message and some other unique data in the view
    }
    catch (ServiceLayerException) {
      // set the message in the view
    }
    // system exceptions, and unrecoverable exceptions are allowed to bubble 
    // up the call stack so a general error can be shown to the user, rather 
    // than showing the form again.
    

    Using inheritance in your own exception classes means you are not required to catch multipile exceptions in your presenter -- you can if there's a need to -- and you don't end up accidentally catching exceptions you can't handle. If your presenter is already at the top of the call stack, add a catch( Exception ) block to handle the system errors with a different view.

    I always try and think of my service layer as a seperate distributable library, and throw as specific an exception as makes sense. It is then up to the presenter/controller/remote-service implementation to decide if it needs to worry about the specific details or just to treat problems as a generic error.

提交回复
热议问题