jeudi 28 mai 2015

How to properly throw and handle exceptions with web services REST c#

I'm following MVC pattern in my Application server. I'm trying to throw an exception but its not been properly thrown.

Here is the code from controller:

[HttpPost]
public IHttpActionResult PostAddSuperUser(SuperUserViewModel SU)
{
    try
    {
        //more code
        blHandler.addSuperUser((SuperUser)SU.user, SU.Password);
        return Ok();
    }
    catch (EUserAlreadyExist ex)
    {
        var resp = new HttpResponseMessage(HttpStatusCode.NotAcceptable);
        resp.Content = new StringContent(string.Format("Already exist ", SU.user.Mail));
        resp.ReasonPhrase = "Already exist";
        throw new HttpResponseException(resp);
    }

Then the client side calls it as follow:

        try{
                    HttpClient client = new HttpClient();
                    client.BaseAddress = new Uri("http://localhost:50687/");

                    HttpResponseMessage response = await client.PostAsJsonAsync<SuperUserViewModel>("/api/SuperUser/PostAddSuperUser", SUVM);

                    if (response.IsSuccessStatusCode)
                    {
                        new SuccesPupUp("", "SuperUser " + SupUserName + " was added");
                    }
                    this.Close();
                }
        }
        catch (HttpResponseException Exc)
        {
            new ErrorPopUp("", Exc.Message);
        }

According to this this I'm throwing it correctly, but when I run it I got this errorenter image description here

How can I fix it?




Aucun commentaire:

Enregistrer un commentaire