Tuesday, 5 November 2024

APIexceptionglobal class

 The ApiExceptionFilter class implements IExceptionFilter, which allows it to catch and handle exceptions globally in an ASP.NET Core application. This class is useful for creating a consistent error-handling mechanism for API responses. Here’s a breakdown of how it works:

1. Class Structure and Dependencies

csharp
public class ApiExceptionFilter : IExceptionFilter { private readonly IHostingEnvironment _hostingEnvironment; private readonly IModelMetadataProvider _modelMetadataProvider; public ApiExceptionFilter(IHostingEnvironment hostingEnvironment, IModelMetadataProvider modelMetadataProvider) { _hostingEnvironment = hostingEnvironment; _modelMetadataProvider = modelMetadataProvider; }
  • Constructor Dependencies: The class constructor accepts two dependencies:
    • IHostingEnvironment: Provides environment-specific information (e.g., Development, Production).
    • IModelMetadataProvider: Used to handle and interact with model metadata, though it’s not directly used in this filter. It may be intended for future enhancements or customization based on model metadata.

2. Exception Handling Logic

The core functionality is in the OnException method, which processes exceptions thrown during the execution of API requests.

csharp
public void OnException(ExceptionContext context) { if (context.Exception is DuplicateRecordException) { context.ModelState.AddModelError(string.Empty, context.Exception.Message); context.Result = new BadRequestObjectResult(context.ModelState.Errors()); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest; }
  • DuplicateRecordException: If the exception is of type DuplicateRecordException, it’s assumed to represent a bad request due to a duplicate entry (e.g., duplicate record error in the database). The filter:
    • Adds the error message to ModelState.
    • Sets Result to BadRequestObjectResult, which returns an HTTP 400 (Bad Request) response with the error details.
    • Sets StatusCode to 400.
csharp
else if (context.Exception is UnAuthorisedAccessException) { context.ModelState.AddModelError(string.Empty, context.Exception.Message); context.Result = new UnauthorizedObjectResult(context.ModelState.Errors()); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; }
  • UnAuthorisedAccessException: If the exception is of type UnAuthorisedAccessException, it’s treated as an unauthorized access error (e.g., insufficient permissions). The filter:
    • Adds the error message to ModelState.
    • Sets Result to UnauthorizedObjectResult, returning an HTTP 401 (Unauthorized) response with the error details.
    • Sets StatusCode to 401.
csharp
else { context.ModelState.AddModelError(string.Empty, context.Exception.Message); context.Result = new ObjectResult(context.ModelState.Errors()); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError; } }
  • General Exception Handling: For other unhandled exceptions, the filter:
    • Adds the error message to ModelState.
    • Sets Result to ObjectResult, which returns a generic error response.
    • Sets StatusCode to 500 (Internal Server Error), indicating an unexpected issue on the server side.

Summary

The ApiExceptionFilter class provides a consistent way to handle specific exceptions in the application by setting a custom error response and appropriate HTTP status code based on the exception type. This approach allows for clear API error responses, which are particularly helpful for client applications that consume the API, as they can handle these errors appropriately.

No comments:

Post a Comment

7 Common mistakes in Dot Net — You can avoid

  There are many common mistakes made during .NET (ASP.NET, .NET Core) development, which affect performance, security, and code… Code Crack...