Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling in Web API

In my Web API project, I created sub projects (class libraries) where I handle actual data handling operations. My backend database is DocumentDB.

My question is how do I tell my Web API action methods of any errors I may encounter within data methods in my class libraries? Once my Web API method knows about the error, I can just return Http status 500 or something like that but I'm not sure what I should have in the catch part (see below) and how I can notify the calling Web API method of the error encountered?

--- Web API Method ---

public async Task<IHttpActionResult> DoSomething(Employee emp)
{
   var employeeRecord = await MyClassLibrary.DoSomethingWithEmployee(emp);

   // Here, I want to check for errors
}

--- Class Library Code ---

public static async Task<Employee> DoSomethingWithEmployee(Employee emp)
{
   try
   {
      // Logic here to call DocumentDB and create employee document
   }
   catch
   {
      // This is where I catch the error but how do I notify the calling Web API method that there was an error?
   }
}
like image 211
Sam Avatar asked Nov 25 '14 21:11

Sam


People also ask

What is exception handling in Web API?

Exceptions are the errors that happen at runtime. Exception handling is the technique to handle this runtime error in our application code. If any error is thrown in web API that is caught, it is translated into an HTTP response with status code 500- "Internal Server Error". There are many ways to handle the exception.

What are the ways of exception handling API?

In ASP.NET MVC Web API, we may have three ways to handle exceptions: HttpResponseException, associated with HttpStatusCode, --- Locally in Try-catch-final. Exception filter, --- in the level of Action, Controller, and Globally. Exception Handler, --- Globally.

How do I return an exception from Web API?

Return InternalServerError for Handled Exceptionscs file and locate the Get(int id) method. Add the same three lines within a try... catch block, as shown in Listing 2, to simulate an error. Create two catch blocks: one to handle a DivideByZeroException and one to handle a generic Exception object.

What is exception handling Handling?

Exception handling is the process of responding to unwanted or unexpected events when a computer program runs. Exception handling deals with these events to avoid the program or system crashing, and without this process, exceptions would disrupt the normal operation of a program.


1 Answers

ASP.NET Web API 2.1 have framework support for global handling of unhandled exceptions.

It allows use to customize the HTTP response that is sent when an unhandled application exception occurs.

So, do not catch exception in Class Library. If you are required to log exception in Class Library, then re-throw those exception to Presentation.

WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // ...

        config.Services.Replace(typeof (IExceptionHandler), 
            new GlobalExceptionHandler());
    }
}

GlobalExceptionHandler

public class GlobalExceptionHandler : ExceptionHandler
{
    public override void Handle(ExceptionHandlerContext context)
    {
        var exception = context.Exception;

        var httpException = exception as HttpException;
        if (httpException != null)
        {
            context.Result = new CustomErrorResult(context.Request,
                (HttpStatusCode) httpException.GetHttpCode(), 
                 httpException.Message);
            return;
        }

        // Return HttpStatusCode for other types of exception.

        context.Result = new CustomErrorResult(context.Request, 
            HttpStatusCode.InternalServerError,
            exception.Message);
    }
}

CustomErrorResult

public class CustomErrorResult : IHttpActionResult
{
    private readonly string _errorMessage;
    private readonly HttpRequestMessage _requestMessage;
    private readonly HttpStatusCode _statusCode;

    public CustomErrorResult(HttpRequestMessage requestMessage, 
       HttpStatusCode statusCode, string errorMessage)
    {
        _requestMessage = requestMessage;
        _statusCode = statusCode;
        _errorMessage = errorMessage;
    }

    public Task<HttpResponseMessage> ExecuteAsync(
       CancellationToken cancellationToken)
    {
        return Task.FromResult(_requestMessage.CreateErrorResponse(
            _statusCode, _errorMessage));
    }
}

Credit to ASP.NET Web API 2: Building a REST Service from Start to Finish, and source code.

like image 87
Win Avatar answered Oct 02 '22 21:10

Win