Welcome to the "Web API with AJAX" article series, here we have been explaining various concepts related to AJAX and the Web API that is the latest technology for Microsoft's communication platform. We have explained RESTful services and various ways to consume it using the ajax() function. You can read the complete article here.
- Web API with AJAX: Understand POST request in Web API
- Web API with AJAX: Understand GET request in Web API
- Web API with AJAX: Make PUT Request in RESTful Web API Service
- Web API With AJAX: Understand DELETE Verb in Restful Web API
- Web API With AJAX: Use GetJSON() Function to Get JSON Data
- Web API with AJAX: Understand Method Name and Attribute in Web API
- Web API with AJAX: Understand FormBody and FormUri attribute inWeb API
- Web API With AJAX: Understand AcceptVerb Attribute in Web API
- Web API With AJAX: Various Parameters of jQuery Ajax() Function
In this article we will learn to handle exceptions in the Web API. I hope this article will help you in your day to-day programming life and programmers will able to implement the concept in their application. So, let's start our explanation.
We know that exception handling is very very (yes, 2 times; not a mistake) important concept in any application. The common misconception of the novice programmer is that, "a good programmer's code never throws an exception" But this is not true at all. A good programmer's code handles exceptions efficiently and no one knows when an exception will be raised.
So, we cannot prevent exceptions but we can handle exceptions. When the code is in the same environment, in other words within the same AppPool or Sandbox then the exception handling is easier. But if the application is service-oriented and if an exception is thrown from the service then the mechanism for handling the exception is different.
Let's try with traditional approach
In this example we will try to handle an exception in a traditional way, in other words within a catch block we will catch an exception and then we will re-throw it. Here is the client code to call the API.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>
<head runat="server">
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#Save").click(function () {
$.ajax({
url: 'http://localhost:3413/api/person',
type: 'POST',
dataType: 'json',
success: function (data, textStatus, xhr) {
console.log(xhr);
},
error: function (xhr, textStatus, errorThrown) {
console.log(textStatus);
}
});
});
});
</script>
</head>
<body>
<input type="button" id="Save" value="Save Data" />
</body>
</html>
Here is the implementation of the Web API.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication1.WebAPI
{
public class personController : ApiController
{
[HttpPost]
public void PostAction()
{
try
{
int zero = 0;
int a = 100 / zero;
}
catch (Exception ex)
{
throw new Exception("Not possible to devide by 0");
}
}
}
}
Please observe that we are generating a "DevideByZero" Exception intentionally and the program is throwing the following exception. Now, observe that the Exception was unhandled by the user, that's fine.
In the error message from the ajax() function we are getting a generalized message "Internal Server Error" rather than "DevideByZeroException" or our custom message returned by a new exception object.
So, we are not getting a prompt with an actual exception. Ok, then this is not the correct way to handle exceptions in the Web API.
Handle exception in proper way
The title is not relevant, rather than the proper way I should write some technical description of that. Anyway we will see the actual way to handle an exception in the Web API. Here is the client code.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="APICall.aspx.cs" Inherits="WebApplication1.APICall" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
$("#Save").click(function () {
$.ajax({
url: 'http://localhost:3413/api/person',
type: 'POST',
dataType: 'json',
success: function (data, textStatus, xhr) {
console.log(xhr);
},
error: function (xhr, textStatus, errorThrown) {
console.log(textStatus);
}
});
});
});
</script>



Jatin ShashooPosted Mar 26, 2015, 7:54 AM
Hey could u give me a java alternative for var resp = new HttpResponseMessage(HttpStatusCode.ExpectationFailed)
Vithal WadjePosted Sep 24, 2014, 11:22 AM
great one
sanjay guptaPosted Dec 11, 2013, 7:36 AM
Thanks sir. very helpful