ttmind

Main Navigation

ttmind
  • jim-jams
  • Tech
  • Positive
Login

Login

Facebook Google

OR

Remember me Forgot password?

Don't have account? Signup here.

Sort by Categorys

.Net

PHP

Java

JavaScript

Database

Server

Client Side

Tools

Artificial Intelligence

Cloud

Hybrid Development

Event

Smart City

Education

Security

Scrum

Digital Marketing

APP Development

Business

Internet

Simulation

Art

Network

Microservices

Architecture

Technology

Leadership

    Top Articles

  • How Does Social Media Bring People Together?
    TTMind Author
  • How to read appSettings JSON from Class Library in ASP.NET Core
    Anil Shrestha
  • Printing Support In Asp.Net Core
    TTMind Author
  • HOW TO EXTRACT TEXT FROM IMAGE USING JAVASCRIPT (OCR with Tesseract.js)?
    Prakash Pokhrel
  • Images Upload REST API using ASP.NET Core
    Prakash Pokhrel
  • Related Topic

  • How to read appSettings JSON from Class Library in ASP.NET Core
  • Printing Support In Asp.Net Core
  • Images Upload REST API using ASP.NET Core
  • How to use IActionFilter, IAsyncActionFilter in ASP.NET Core MVC?
  • ASP.NET CORE - Blazor CRUD operation using ADO.NET
  • Tech
  • About Us
  • Contact Us
  • TechHelp
  • PositiveHelp
  • Jim-Jams Help
  • Terms & Conditions

© Copyright ttmind.com

Main Content

ASP.NET Core Web API Exception Handling?

.Net .Net Core about 7 years ago || 8/10/2018 || 2.3 K View

  • Hide

The exception handling features support us to deal with the unexpected errors which could arise in our code. We can use the try-catch and finally block in our code to handle the exceptions.

we can extract all the exception handling logic into a single centralized place even when there is nothing wrong with the try-catch block in our Web API project. Doing this, our actions can be made more readable and the error handling process more maintainable.

In this article, we are handling errors by using middleware for global error handling to show the benefits of this approach.

let us begin by creating a custom exception filter class (for my code: GlobalExceptionFilter is custom filter class) by using Interface: IExceptionFilter or IExceptionFilterAsync. 

public class GlobalExceptionFilter: IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            throw new NotImplementedException();
        }
    }

Now we must define the OnException method as per our requirements(to handle Exception).

 public class GlobalExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            HttpStatusCode status = HttpStatusCode.InternalServerError;
            var message = "Internal Server Error ";

            var exceptionType = context.Exception.GetType();
            if (exceptionType.FullName is "System.IndexOutOfRangeException")//my custom exception type
            {
                message = context.Exception.Message;
            }
            context.ExceptionHandled = true;
            HttpResponse response = context.HttpContext.Response;
            response.StatusCode = (int)status;
            response.ContentType = "application/json";
            context.Result = new ObjectResult(new ApiResponse() { Message = message, Data = null });
        }
    }

public class Response
    {
        public string Message { get; set; }
        public object Data { get; set; }
    }

In Above example, if an exception is a custom (For demo "IndexOutOfRangeException" is handled) type then we will pull exception message from exception object else we will just send "Internal Server Error " as a general message and at last, we return Response object wrapping by ObjectResult.  The response is a class contains two property Message and Data. As shown on Above code, once an Exception was handled, we must set ExceptionHandled Property of ExceptionContext to true.

Now, let us register our " TestExceptionFilter" in ConfigureServices on "Startup.cs", which helps us to handle the exception occur in Web API globally.

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                config.Filters.Add(typeof(TestExceptionFilter));
            });
        }

Let us add controller to test our code, and added two methods.

[Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
                int a = 12;
                int c = a / 0;
                return new string[] { "value1", "value2" };
        }
        //  GET api/values/5
        [HttpGet("{id}")]
        public IEnumerable<string> Get(int id)
        {
                int[] a = new int[] { 1, 2, 3 };
                return new string[] { "value1", "value2", a[id].ToString() };
        }        
    }

Let us Run our WebAPI. On URL “http://localhost:65007/api/values”

As previously mentioned, the general message "Internal Server Error " was seen.

Again, on URL “http://localhost:65007/api/values/5”. We can see

Conclusion:

In this article, we learned how to Handle Exception on ASP.NET Core Web API.

 

Happy Coding!!!

  • 0
  • 0
  • 0
    • Facebook
    • Twitter
    • Google +
    • LinkedIn

About author

Prakash Pokhrel

Prakash Pokhrel

https://np.linkedin.com/in/prakash-pokhrel-42a699a2

Reset Your Password
Enter your email address that you used to register. We'll send you an email with your username and a link to reset your password.

Quick Survey