Handle errors in Web API

0

Category :

Using HttpResponseException

You can use the HttpResponseException class to return specific HTTP status code and messages from your controller methods in Web API.

var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
 Content = new StringContent("Employee doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
 StatusCode = HttpStatusCode.NotFound
}
throw new HttpResponseException(response); 

Using HttpError

You can use the CreateErrorResponse extension method in your Web API controller method to return meaningful error codes and error messages. The CreateErrorResponse method creates an HttpError object and then wraps it inside an HttpResponseMessage object.

string message = "Employee doesn't exist";
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message)); 

Using Exception filters

Exception filters are filters that can be used to handle unhandled exceptions that are generated in your Web API controller methods. global error filter is a good approach to handle exceptions in your Web API if unhandled exceptions are thrown and not handled in your controller methods.

To create an exception filter you need to implement the IExceptionFilter interface. You can also create exception filters by extending the abstract class ExceptionFilterAttribute and then overriding the OnException method. Note that the ExceptionFilterAttribute abstract class in turn implements the IExceptionFilter interface.

how you can create a custom exception filter by extending the ExceptionFilterAttribute class and then overriding the OnException method.
public class CustomExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            HttpStatusCode status = HttpStatusCode.InternalServerError;

            String message = String.Empty;
            var exceptionType = actionExecutedContext.Exception.GetType();

            if (exceptionType == typeof(UnauthorizedAccessException))
            {
                message = "Access to the Web API is not authorized.";
                status = HttpStatusCode.Unauthorized;
            }
            else if (exceptionType == typeof(DivideByZeroException))
            {
                message = "Internal Server Error.";
                status = HttpStatusCode.InternalServerError;
            }
            else if (exceptionType == typeof(InternalApiException))
            {
                message = "Internal Server Api Exception.";
                status = HttpStatusCode.InternalServerError;
            }
            else
            {
                message = "Not found.";
                status = HttpStatusCode.NotFound;
            }

            actionExecutedContext.Response = new HttpResponseMessage()
            {
                Content = new StringContent(message, System.Text.Encoding.UTF8, "text/plain"),
                StatusCode = status
            };

            base.OnException(actionExecutedContext);
        }
    }
You should add the custom exception filter to the filters collection of the HttpConfiguration object.
public static void Register(HttpConfiguration config)
{ 
 config.Filters.Add(new CustomExceptionFilter());
You can register your exception filters in one of the following three ways: At the action level
public class EmployeesController : ApiController
{
    [NotImplementedExceptionFilter]
    public Employee GetEmployee(int id) 
At the controller level
[DatabaseExceptionFilter]
public class EmployeesController : ApiController
{ 
Globally
GlobalConfiguration.Configuration.Filters.Add(new DBFilterAttribute());


my thanks to this great article:
https://www.infoworld.com/article/2994111/application-architecture/how-to-handle-errors-in-web-api.html

0 comments:

Post a Comment