Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

时间:2021-09-28 08:00:34

A benefit of using ASP.NET Web API is that it can be consumed by any client with the capability of making HTTP calls and processing JSON data. The client can use HTTP methods to perform Read/Write operations. They make use of HttpRequestMessage and HttpResponseMessage to manage messaging to and from Web API. For each action method, Web API uses IHttpActionResult type to manage responses with HttpStatusCode.

Since the HttpStatusCode is pre-configured for default HTTP error codes like 500, 403, etc, it is a challenge to respond with the exact exception that occurred on the server-side while processing a request. This challenge can be addressed by implementing Exception filter on the Web API Controller. The exception filter will catch all errors that happens inside an action while it is executing.

When the ApiController (the base class for the Web API) executes an action from the class, it loads the ExceptionFilterResult if an exception occurs during the execution. The ExceptionFilterResult implements IHttpActionResult. The ExceptionFilterResult catches all exception and then passes these exceptions to the Exception Filter attribute. We have the liberty to implement the Exception filter as per the logical requirements of our application.

The following diagram gives an idea of the exception filter process:

Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

Lets’ implement a custom Exception Filter in a Web API controller class.

Step 1: Open the free Visual Studio 2013 Community Edition (or any other VS 2013/2015 edition of your choice) and create a new Web API application of the name WEBAPI_Exception. In this project in the App_Data folder, add a new SQL Server database of name Application.mdf. In this database add a new EmployeeInfo table with following schema:

CREATE TABLE [dbo].[EmployeeInfo] (
[EmpNo] INT IDENTITY (1, 1) NOT NULL,
[EmpName] VARCHAR (50) NOT NULL,
[Salary] INT NOT NULL,
[DeptName] VARCHAR (50) NOT NULL,
[Designation] VARCHAR (50) NOT NULL,
PRIMARY KEY CLUSTERED ([EmpNo] ASC)
);

Step 2: In the models folder add a new ADO.NET Entity Data Model. Name this as ApplicationEDMX. In the wizard, select Application.mdf and select EmployeeInfo table. After completing this wizard, the project will generate table mapping for EmployeeInfo table as shown in the following diagram:

Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

Step 3: In the project add a new folder of the name CustomFilterRepo. In this folder add a new class file with the following code. This code contains class derived from the Exception base class and contains constructor for exception message.

using System;

namespace WEBAPI_Execption.CustomFilterRepo
{
/// <summary>
/// The base Exception Class
/// </summary>
public class ProcessException : Exception
{
public ProcessException(string message)
: base(message)
{ }
}
}

Step 4: In the CustomFilterRepo folder add a new class file with the following code:

using System.Net;
using System.Net.Http;
using System.Web.Http.Filters; namespace WEBAPI_Execption.CustomFilterRepo
{
/// <summary>
/// The Custom Exception Filter
/// </summary>
public class ProcessExceptionFilterAttribute : ExceptionFilterAttribute,IExceptionFilter
{
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
//Check the Exception Type if (actionExecutedContext.Exception is ProcessException)
{
//The Response Message Set by the Action During Ececution
var res = actionExecutedContext.Exception.Message; //Define the Response Message
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.InternalServerError) {
Content = new StringContent(res),
ReasonPhrase = res
}; //Create the Error Response actionExecutedContext.Response = response;
}
}
}
}

This class is derived from ExceptionFilterAttribute base class. This allows you to implement a custom exception filter in Web API. The above code checks the exception occurred during action processing using HttpActionExecutedContext object. This object reads the exception message set to the Message property of the exception class in the action method. Finally this information is returned using the Response property of the HttpActionExecutedContext.

Step 5: In the Models class add a new class file with following code:

using System.ComponentModel.DataAnnotations;
namespace WEBAPI_Execption.Models
{
[MetadataType(typeof(EmployeeInfoMetadata))]
public partial class EmployeeInfo
{
private class EmployeeInfoMetadata
{
public int EmpNo { get; set; }
[Required(ErrorMessage = "Value is Must")]
public string EmpName { get; set; }
[Required(ErrorMessage = "Salary is Must")]
public int Salary { get; set; }
[Required(ErrorMessage = "DeptName is Must")]
public string DeptName { get; set; }
[Required(ErrorMessage = "Designation is Must")]
public string Designation { get; set; }
} }
}

The above data annotations defines validation rules on properties of EmployeeInfo Class. We will be requiring this for POST operations.

Step 6: In the Controllers folder add a new empty Web API controller of the name EmployeeInfoAPIController. Add the following code in the Web API Controller class:

using System.Net;
using System.Net.Http;
using System.Web.Http;
using WEBAPI_Execption.Models;
using WEBAPI_Execption.CustomFilterRepo;
using System.Web.Http.Description; namespace WEBAPI_Execption.Controllers
{ /// <summary>
/// Apply the Exception Filter at the Class level
/// </summary>
public class EmployeeInfoAPIController : ApiController
{
ApplicationEntities ctx; public EmployeeInfoAPIController()
{
ctx = new ApplicationEntities();
}
[ResponseType(typeof(EmployeeInfo))]
public IHttpActionResult Get(int id)
{
var emp = ctx.EmployeeInfoes.Find(id); if (emp == null)
{
throw new ProcessException("Record Not Found, It may be removed");
}
return Ok(emp);
} [ResponseType(typeof(EmployeeInfo))]
public IHttpActionResult Post(EmployeeInfo employeeInfo)
{
if (!ModelState.IsValid)
{
//Throw the Exception by settings Error Message throw new ProcessException("One or more entered values are invalid, please check");
} ctx.EmployeeInfoes.Add(employeeInfo);
ctx.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = employeeInfo.EmpNo }, employeeInfo);
}
}
}

In the above code, the Get() action method accepts id parameter and looks for the Employee based on id, if the record is not present then this will throw the ProcessException with an error message. The Post() action method accepts EmployeeInfo object and validates it before saving it in a database. If the validation fails, then the ProcessException is thrown with an error message.

Step 7: To handle exceptions, we need to register a custom exception filter. Open WebApiConfig.cs file and add the exception filter in HttpConfiguration as shown in the following code:

config.Filters.Add(new ProcessExceptionFilterAttribute());

Step 8: In the project add the jQuery library using NuGet Package.

Step 9: In the Controllers folder, add an empty MVC controller of the name TestController. Scaffold Index.cshtml from the Index () action method of this controller. In the Index.cshtml add the following code:

@{
ViewBag.Title = "Index";
} <script src="~/Scripts/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btnget").on('click', function (){
$.ajax({
url: "http://localhost:49747/api/EmployeeInfoAPI/1999",
type:"GET"
}).done(function (resp) {
alert("EmpNo" + resp.EmpNo + " EmpName " + resp.EmpName);
}).error(function (xhr, textStatus, errorThrown) {
alert("Err " + textStatus + " " + errorThrown);
}); }); $("#btnpost").on('click', function () {
var Emp = {};
Emp.EmpName = "MM";
// Emp.Salary = 12300;
Emp.DeptName = "SYS";
Emp.Designation = "MGR"; $.ajax({
url: "http://localhost:49747/api/EmployeeInfoAPI",
type: "POST",
data: Emp,
datatype: "json",
contenttype:"application/json;utf-8"
}).done(function (resp) {
alert("Record Added" + resp.EmpNo);
}).error(function (xhr, textStatus, errorThrown) {
alert("Err " + errorThrown);
}); });
});
</script> <h2>Index</h2>
<table class="table table-bordered table-striped">
<tr>
<td>Click Here to Received the Employee</td>
<td>
<input type="button" id="btnget" value="Get" />
</td>
</tr>
<tr>
<td>
Click Here to Post the Employee
</td>
<td>
<input type="button" id="btnpost" value="Post" />
</td>
</tr>
</table>

In the above view, the Html button defines a click event to make an Ajax call to Web API. Note the URL for Web API is hard-coded. The .error() callback for Ajax call accepts errorThrown parameter which will be used to display actual error thrown on the server. The database does not contain EmpNo as 1999, so this call will definitely fail.

Run the view.

Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

Click on the Get button, this will throw exception as follows:

Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

This shows the Error Message as Record Not Found, it may be removed. Continuing debugging here and it will show the error captured by Ajax in an alert box:

Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

This shows the actual error message thrown in exception on the Server by Web API.

Similarly in the Post button click, the JavaScript object Emp is declared and it is used to post Employee record to Web API. The code has Emp.Salary expression as commented out, this means that Salary will not be posted to the Server. In Step 5 we have applied DataAnnotations on EmployeeInfo object with [Required] attribute on the Salary property. Since we are not passing Salary with the POST request, our call will fail with actual server side exception message as following:

Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

This shows a server side error message as One or more entered values are invalid please check. Continue execution, the client side alert box will display error as following:

Custom Exception in ASP.NET Web API 2 with Custom HttpResponse Message

That’s it.

Conclusion: Custom Exception filters acts as a value addition in ASP.NET Web API to manage custom messages to be sent to the client application.

Download the entire source code of this article (Github)