3

Currently, I'm doing the following to send error messages back to the client:

HttpResponseMessage message = new HttpResponseMessage(HttpStatusCode.Forbidden)
{
    ReasonPhrase = "No rights to access this resource",
};

throw new HttpResponseException(message);

However, I would like to improve the response further by sending back custom exceptions. So I can have something like this:

public class MyAppException : Exception {}

public class NoRightsException : MyAppException {}
public class SaveException : MyAppException {}    
//etc...

All my exceptions will be in a separate assembly that will be reference by both the server and the client.

How is the best to return these exceptions to the client and how will the client have to check whether the response is my custom exception, another exception or simply a text message?

Ivan-Mark Debono
  • 15,500
  • 29
  • 132
  • 263
  • 1
    This might help you read here http://stackoverflow.com/questions/10732644/best-practice-to-return-errors-in-asp-net-web-api Especially the example where it has explained used of Request.CreateResponse method – Vikram Shetty Nov 03 '14 at 16:52

1 Answers1

1

To answer the first part of your question..the correct way to return exceptions is to use Request.CreateErrorResponse. This method has a number of overloads one of which takes the exception as a parameter. In your case you might do...

Request.CreateErrorResponse(HttpStatusCode.BadRequest, new NoRightsException());

Update:

Although you haven't stated what your client method is I'm going to assume you are using HttpClient. If this is the case you should be making a call similiar to this...

var client = new HttpClient();

var task = client.PostAsync(url)
            .ContinueWith(response =>
            {
                response.Result.EnsureSuccessStatusCode();
            });

task.Wait();

in which case you will find the text or the exception in the response class

tom redfern
  • 30,562
  • 14
  • 91
  • 126
Simon Ryan
  • 212
  • 1
  • 9
  • 1
    I'm using HttpClient. The custom exception is not deserialized at all. All I can see is that the response throws an exception with BadRequest status code. – Ivan-Mark Debono Nov 04 '14 at 08:45
  • I've not used it to pass back exceptions. The pattern I use is to log the exception on the server, and the client will display a generic error page if the request has not resulted in a HttpResponse.OK – Simon Ryan Nov 04 '14 at 10:23