Friday, December 14, 2018

Exception in Web API

Summary
We can use HttpResponseException when the possibility of exception is known by us. In the above example, we have thrown exception using HttpResponseException class as we know there is a chance to employee not found in the database.

We can use exception filter to catch unhandled exceptions on action/controllers.

We can use Exception Handlers to catch any type of unhandled exception application-wide.

Detail

There are many ways to handle the exception. 

Using HttpResponseException

This exception class allows us to return HttpResponseMessage to the client. It returns HTTP status code that is specified in the exception Constructor. 

For example, the following method of EmployeeController returns Status code 404 (not found), if employee data is not found for ID.

public Employee Get([FromODataUri] int key)  
{  
    Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
  
    if (data == null)  
    {  
        var response = new HttpResponseMessage(HttpStatusCode.NotFound)  
        {  
            Content = new StringContent(string.Format("No Employee found with ID = {0}", key)),  
                ReasonPhrase = "Employee Not Found"  
        };  
  
        throw new HttpResponseException(response);  
    }  
    return data;  


Using HttpError

CreateErrorResponse method of Request object helps us to return meaningful error code and message to the client. CreateErrorResponse creates an instance of HttpError object and returns it as HttpResponseMessage object.
public HttpResponseMessage Get([FromODataUri] int key)  
{  
    Employee data = context.Employees.Where(k => k.Id == key).FirstOrDefault();  
    if (data == null)  
    {  
        string message = string.Format("No Employee found with ID = {0}", key);  
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);  
    }  
    return Request.CreateResponse(HttpStatusCode.OK, data);;  
}  

Using Exception Filters

Exception filters can be used to handle unhandled exceptions which are generated in Web API. The exception filter can be able to catch the unhandled exceptions in Web API. This filter is executed when an action method throws the unhandled exception. Note that exception filter does not catch HttpResponseException exception because HttpResponseException is specifically designed to return the HTTP response.

namespace WebAPITest  
{  
    using System.Net;  
    usingSystem.Net.Http;  
    usingSystem.Web.Http.Filters;  
  
    public class CustomExceptionFilter: ExceptionFilterAttribute  
    {  
        public override void OnException(HttpActionExecutedContextactionExecutedContext)  
        {  
            string exceptionMessage = string.Empty;  
            if (actionExecutedContext.Exception.InnerException == null)  
            {  
                exceptionMessage = actionExecutedContext.Exception.Message;  
            }  
            else  
            {  
                exceptionMessage = actionExecutedContext.Exception.InnerException.Message;  
            }  
            //We can log this exception message to the file or database.  
            var response = newHttpResponseMessage(HttpStatusCode.InternalServerError)  
            {  
                Content = newStringContent(“An unhandled exception was thrown by service.”),  
                    ReasonPhrase = "Internal Server Error.Please Contact your Administrator."  
            };  
            actionExecutedContext.Response = response;  
        }  
    }  
}  


Register Exception Filters

Decorate Action with exception filter.
Decorate Controller with exception filter.
Filter Register globally.

To apply the exception filter to all Web API controllers, the filter needs to register to GlobalConfiguration.Configuration.Filters collection.
public static class WebApiConfig  
{  
    public static void Register(HttpConfigurationconfig)  
    {  
        config.Filters.Add(newCustomExceptionFilter());  
    }  
}  

Using Exception Handlers

Normally, exception filter is used to catch the unhandled exception. This approach will work fine but it fails if any error is raised from outside action. For example, if any error is raised in the following area then exception filter will not work.
Error inside the exception filter.
Exception related to routing.
Error inside the Message Handlers class.
Error in Controller Constructor.


https://www.c-sharpcorner.com/article/exception-handling-in-asp-net-web-api/

No comments:

Followers

Link