We know that Web API is the Microsoft’s latest solution of
service oriented architecture. It’s simple, light and fast data transferring
solution which uses JSON mostly over HTTP. The transferred data is not as bulky
as SOAP. Those who are experience in SOAP messaging era they might familiar
with SOAP fault which is just another XML message contains detail of error including
stack tress and current request context. It makes developer’s life very easy and
gives handsome clue to investigate farther.
The scenario is bit different in case of Web API. We know
Web API make response in terms of HTTP code. The pattern tries to adapt REST
style of service exposure. So, let’s quickly discuss the boundary of status
code and after that we will implement exception handling mechanism. The status
code is nothing but integer number which indicates the response type by server.
It’s for client, to detect status of HTTP response.
1XX series for Information
This is used very less in reality. For example: 100 for
continue. Information about response received, continue processing etc.
2XX series for success
This series is mostly used one, like 200 for success
which we can send from any successful HTTP response. 201 for created when we created
resource successfully in server.
3XX for Redirection
The example of this series is, 300 for Multiple choices, 301
for Moved permanently, 303 for See Other etc.
4XX for Client Error
Response of this series is very common one. This is all
about client error. Like 400 for Bad Request, 401 for Unauthorized, 403 for Forbidden,
404 for resource not found and many more.
5XX for server error
This is another very common error section; this series of
error is all about server. The example is 500 for internal server error which
wrap all other internal error. For example,501 for Not Implemented, 502 for Bad
Gateway, 503 for Service unavailable etc.
Ok, so we got quick
idea about status code and its series. Now, the question is that if my
application throws divideByZero exception in time of division, what should be
the status code? We can consider this is an internal operation related error
and we can wrap the exception message by HTTP response and attach 500 status
code to it.
When client will receive the message, it can able to extract
the inner exception from HTTP response itself.
Another scenario is, What if, we want to throw our custom
exception from application?
In that kind of scenario we can return 500 as internal sever
error and wrap the exception by HTTP response.
Return exception
message from Web API 1.0
In this example we will generate HTTP response message in
context of Web API 1.0. We can use HttpResponseMessage as return type of action.
Here is sample implementation.
public HttpResponseMessage Get()
{
try
{
throw new Exception("I am throwing this exception");
}
catch (Exception ex)
{
HttpError errorMessage = new HttpError(ex.Message);
return Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError,
errorMessage);
}
}
We are using fiddler as client and once we go to JSON tab,
we will see the actual exception message which we have attach in response body
of HTTP response message.
This is the example we will try with one application
exception. Here we will implement code for DivideByZero exception. Have a look
on below code.
public HttpResponseMessage Get()
{
try
{
throw new DivideByZeroException();
}
catch (DivideByZeroException ex)
{
HttpError errorMessage = new HttpError(ex.Message);
return Request.CreateResponse(System.Net.HttpStatusCode.InternalServerError,
errorMessage);
}
}
In this time, we will click on Raw tab to check the actual
HTTP response message. We are seeing that in header the status code 500 is
attached, means internal server error.
In response body, we are seeing the actual response message
in JSON format.
Return exception
message from Web API 2.0
We know that web API 2.0 gives the feature of IHttpActionResult
as response type. The interface contains
only one method called ExecuteAsync. Let’s see what is IHttpActionResult and what
facility it may give to us?
IHttpActionResult is interface and one of the concrete
implementation is Exception result.
The ApiController contains one helper function called
InternalServerError which takes one argument of Exception type and returns
object of ExceptionResult type.
Now, as ExceptionResult is the concrete implementation of
IHttpActionResult, we can use IHttpExceptionResult as return type of action and
can use InternalServerError helper function to return ExceptionResult object
which will act as a rapper of actual Exception object and the HTTP response
will transfer to client. So, let’s implement it and see in action.
public IHttpActionResult Get()
{
try
{
throw new Exception("Exception from Web API 2.0");
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
In catch block we are returning internal server error
exception response by single line of statement. Just we are using the helper function and
internally it will create full blown HTTP response message with internal server
error (500) status code. Here is the response in JSON format.
We can check the raw message too. It’s just like first
example. Status code is attach in response body and status message is attached
in HTTP response body.
Call Web API from
.NET client
So far we have used fiddler to consume Web API service, now
we will see how, we can get the status information of HTTP response from .NET
client. Here is sample code.
public static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:29668/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync("api/Test/").Result;
if (response.IsSuccessStatusCode)
{
//do stuff here.
}
else
{
Console.WriteLine("Error
Type : " + response.StatusCode + "\n");
Console.WriteLine("Error Message : " + response.Content.ReadAsStringAsync().Result); }
Console.ReadLine();
}
In output, we are seeing that it’s showing
InternalServerError.
Conclusion:-
In this article we learned to return our custom exception
message from Web API and learned to consume the exception message from .NET
client. I think it will help you to deal
with exception in Web API.
No comments:
Post a Comment