Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16340

Web API throw custom exception back to client

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?

Upvotes: 3

Views: 9234

Answers (1)

Simon Ryan
Simon Ryan

Reputation: 212

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

Upvotes: 1

Related Questions