Home > Backend Development > C#.Net Tutorial > How to handle errors in middleware C# Asp.net Core?

How to handle errors in middleware C# Asp.net Core?

王林
Release: 2023-09-02 11:01:12
forward
863 people have browsed it

如何处理中间件 C# Asp.net Core 中的错误?

Create a new folder named CustomExceptionMiddleware and a class ExceptionMiddleware.cs is inside.

The first thing we need to do is register the IloggerManager service and Implement RequestDelegate through dependency injection.

The _next parameter of the RequestDeleagate type is a function delegate that can be processed Our HTTP request.

After the registration process, we need to create the InvokeAsync() method RequestDelegate cannot handle requests without it.

_next delegate should handle our controller's request and Get operations should generate a successful response. But if the request fails (and it does fail, Since we are forcing an exception),

our middleware will trigger the catch block and call HandleExceptionAsync method.

public class ExceptionMiddleware{
   private readonly RequestDelegate _next;
   private readonly ILoggerManager _logger;
   public ExceptionMiddleware(RequestDelegate next, ILoggerManager logger){
      _logger = logger;
      _next = next;
   }
   public async Task InvokeAsync(HttpContext httpContext){
      try{
            await _next(httpContext);
      }
      catch (Exception ex){
         _logger.LogError($"Something went wrong: {ex}");
         await HandleExceptionAsync(httpContext, ex);
      }
   }
   private Task HandleExceptionAsync(HttpContext context, Exception exception){
      context.Response.ContentType = "application/json";
      context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
      return context.Response.WriteAsync(new ErrorDetails(){
         StatusCode = context.Response.StatusCode,
         Message = "Internal Server Error from the custom middleware."
      }.ToString());
   }
}
Copy after login

Modify our ExceptionMiddlewareExtensions class with another static method −

public static void ConfigureCustomExceptionMiddleware(this IApplicationBuilder
app){
   app.UseMiddleware<ExceptionMiddleware>();
}
Copy after login

Use this method in the configuration method of the Startup class -

app.ConfigureCustomExceptionMiddleware();
Copy after login

The above is the detailed content of How to handle errors in middleware C# Asp.net Core?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template