<p>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 of concerns.</p>

<p>So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users:</p>

<pre><code>public class CreateMemberPresenter
{
    private ICreateMemberView view;
    private IMemberTasks tasks;

    public CreateMemberPresenter(ICreateMemberView view) 
        : this(view, new StubMemberTasks())
    {
    }

    public CreateMemberPresenter(ICreateMemberView view, IMemberTasks tasks)
    {
        this.view = view;
        this.tasks = tasks;

        HookupEventHandlersTo(view);
    }

    private void HookupEventHandlersTo(ICreateMemberView view)
    {
        view.CreateMember += delegate { CreateMember(); };
    }

    private void CreateMember()
    {
        if (!view.IsValid)
            return;

        try
        {
            int newUserId;
            tasks.CreateMember(view.NewMember, out newUserId);
            view.NewUserCode = newUserId;
            view.Notify(new NotificationDTO() { Type = NotificationType.Success });
        }
        catch(Exception e)
        {
            this.LogA().Message(string.Format("Error Creating User: {0}", e.Message));
            view.Notify(new NotificationDTO() { Type = NotificationType.Failure, Message = "There was an error creating a new member" });
        }
    }
}
</code></pre>

<p>I have my main form validation done using the built in .Net Validation Controls, but now I need to verify that the data sufficiently satisfies the criteria for the Service Layer.</p>

<p>Let's say the following Service Layer messages can show up:</p>

<ul>
<li>E-mail account already exists (failure)</li>
<li>Refering user entered does not exist (failure)</li>
<li>Password length exceeds datastore allowed length (failure)</li>
<li>Member created successfully (success)</li>
</ul>

<p>Let's also say that more rules will be in the service layer that the UI cannot anticipate.</p>

<p>Currently I'm having the service layer throw an exception if things didn't go as planned. Is that a sufficent strategy? Does this code smell to you guys? If I wrote a service layer like this would you be annoyed at having to write Presenters that use it in this way? Return codes seem too old school and a bool is just not informative enough.</p>

<hr>

<blockquote>
  <p><strong>Edit not by OP: merging in follow-up comments that were posted as answers by the OP</strong></p>
</blockquote>

<hr>

<p>Cheekysoft, I like the concept of a ServiceLayerException. I already have a global exception module for the exceptions that I don't anticipate. Do you find making all these custom exceptions tedious? I was thinking that catching base Exception class was a bit smelly but wasn't exactly sure how progress from there.</p>

<p>tgmdbm, I like the clever use of the lambda expression there!</p>

<hr>

<p>Thanks Cheekysoft for the follow-up. So I'm guessing that would be the strategy if you don't mind the user being displayed a separate page (I'm primarily a web developer) if the Exception is not handled.</p>

<p>However, if I want to return the error message in the same view where the user submitted the data that caused the error, I would then have to catch the Exception in the Presenter?</p>

<p>Here's what the CreateUserView looks like when the Presenter has handled the ServiceLayerException:</p>

<p><img src="https://i.stack.imgur.com/HOJU7.png" alt="Create a user"></p>

<p>For this kind of error, it's nice to report it to the same view. </p>

<p>Anyways, I think we're going beyond the scope of my original question now. I'll play around with what you've posted and if I need further details I'll post a new question.</p>

[{'answer_id': 22043, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 5, 'selected': True, 'text': '<p>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.</p>\n\n<p><strong>Don\'t catch Exception</strong></p>\n\n<p>However, <a href="https://stackoverflow.com/questions/21938/is-it-really-that-bad-to-catch-a-general-exception">don\'t catch Exception</a> 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. </p>\n\n<p><strong>Plan a Simple Exception Hierarchy</strong></p>\n\n<p>If you are going to use exceptions in this way, you should design an exception hierarchy for your own exception classes. \nAt 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.</p>\n\n<p>Your presenter then has the option of doing</p>\n\n<pre><code>try {\n  // call service etc.\n  // handle success to view\n} \ncatch (AccountAlreadyExistsException) {\n  // set the message and some other unique data in the view\n}\ncatch (ServiceLayerException) {\n  // set the message in the view\n}\n// system exceptions, and unrecoverable exceptions are allowed to bubble \n// up the call stack so a general error can be shown to the user, rather \n// than showing the form again.\n</code></pre>\n\n<p>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.</p>\n\n<p>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.</p>\n'}, {'answer_id': 22586, 'author': 'tgmdbm', 'author_id': 1851, 'author_profile': 'https://Stackoverflow.com/users/1851', 'pm_score': 2, 'selected': False, 'text': '<p>As Cheekysoft suggests, I would tend to move all major exceptions into an ExceptionHandler and let those exceptions bubble up. The ExceptionHandler would render the appropriate view for the type of exception. </p>\n\n<p>Any validation exceptions however should be handled in the view but typically this logic is common to many parts of your application. So I like to have a helper like this</p>\n\n<pre><code>public static class Try {\n    public static List&lt;string&gt; This( Action action ) {\n      var errors = new List&lt;string&gt;();\n      try {\n        action();\n      }\n      catch ( SpecificException e ) {\n        errors.Add( "Something went \'orribly wrong" );\n      }\n      catch ( ... )\n      // ...\n     return errors;\n    }\n}\n</code></pre>\n\n<p>Then when calling your service just do the following</p>\n\n<pre><code>var errors = Try.This( () =&gt; {\n  // call your service here\n  tasks.CreateMember( ... );\n} );\n</code></pre>\n\n<p>Then in errors is empty, you\'re good to go.</p>\n\n<p>You can take this further and extend it with custome exception handlers which handle <em>uncommon</em> exceptions.</p>\n'}, {'answer_id': 25030, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 1, 'selected': False, 'text': '<p>In reply to the follow-up question:</p>\n\n<p>As for creating exceptions becoming tedious, you kinda get used to it. Use of a good code generator or template can create the exception class with minimal hand editing within about 5 or 10 seconds. </p>\n\n<p>However, in many real world applications, error handling can be 70% of the work, so it\'s all just part of the game really. </p>\n\n<p>As tgmdbm suggests, in MVC/MVP applications I let all my unhandlable exceptions bubble up to the top and get caught by the dispatcher which delegates to an ExceptionHandler. I set it up so that it uses an ExceptionResolver that looks in the config file to choose an appropriate view to show the user. Java\'s Spring MVC library does this very well. Here\'s a snippet from a config file for Spring MVC\'s Exception resolver - its for Java/Spring but you\'ll get the idea.</p>\n\n<p>This takes a huge amount of exception handling out of your presenters/controllers altogether.</p>\n\n<pre><code>&lt;bean id="exceptionResolver"\n      class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver"&gt;\n\n  &lt;property name="exceptionMappings"&gt;\n    &lt;props&gt;\n      &lt;prop key="UserNotFoundException"&gt;\n        rescues/UserNotFound\n      &lt;/prop&gt;\n      &lt;prop key="HibernateJdbcException"&gt;\n        rescues/databaseProblem\n      &lt;/prop&gt;\n      &lt;prop key="java.net.ConnectException"&gt;\n        rescues/networkTimeout\n      &lt;/prop&gt;\n      &lt;prop key="ValidationException"&gt;\n        rescues/validationError\n      &lt;/prop&gt;\n      &lt;prop key="EnvironmentNotConfiguredException"&gt;\n        rescues/environmentNotConfigured\n      &lt;/prop&gt;\n      &lt;prop key="MessageRejectedPleaseRetryException"&gt;\n        rescues/messageRejected\n      &lt;/prop&gt;\n    &lt;/props&gt;\n  &lt;/property&gt;\n  &lt;property name="defaultErrorView" value="rescues/general" /&gt;\n&lt;/bean&gt;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/21697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1894/']