title: Error handling between web api and angular 2 client
body: <p>So I am looking for a pattern on how to handle exceptions.  Specifically I want to be able to pass the exception message on to the client from a Web API controller.</p>
  
  <p>The client is using a third party library which deals with a call to the API
  as </p>
  
  <pre class="lang-js prettyprint-override"><code>this.msgs = [];
  let xhr = new XMLHttpRequest(),
  formData = new FormData();
  
  
  for(let i = 0; i &lt; this.files.length; i++) {
      formData.append(this.name, this.files[i], this.files[i].name);
  }
  
  xhr.upload.addEventListener('progress', (e: ProgressEvent) =&gt; {
      if(e.lengthComputable) {
        this.progress = Math.round((e.loaded * 100) / e.total);
      }
    }, false);
  
  xhr.onreadystatechange = () =&gt; {
      if(xhr.readyState == 4) {
          this.progress = 0;
  
          if(xhr.status == 200)
              this.onUpload.emit({xhr: xhr, files: this.files});
          else
              this.onError.emit({xhr: xhr, files: this.files});
  
          this.clear();
      }
  };
  
  xhr.open('POST', this.url, true);
  xhr.send(formData);
  </code></pre>
  
  <p>My current call back function is such</p>
  
  <pre><code>errorComplete(event: any) {
      console.log("upload error");
  }
  </code></pre>
  
  <p>notice that on error the library just wraps up the XMLHttpRequest and passes it on to my call back function.</p>
  
  <p>so in the controller I have created a test line as follows</p>
  
  <pre><code>throw new Exception("This is a test message");
  </code></pre>
  
  <p>This is to simulate an unexpected exception</p>
  
  <p>currently the return code in the XMLHttpRequest is a 500 and the text is the html that .Net generates when an exception occurs.</p>
  
  <p>yes the method in my controller will need to wrapper in a try-catch but I am not sure of what code to put in the catch so I can send the error message down to the client and it can handle it and not take down the application.</p>
  
  <p>the current use case I am looking at is the user uploads a file to the system but there is already a file with the specified name in the system.  And renaming the file is not an option!  I need to notify the user that there is already a file with that name in the system.</p>
  
  <p>google has not revealed a way to pass the message back so I can process it.</p>