---
# System prepended metadata

title: ExceptionMiddleware => 遇到問題就來寫 Log 吧
tags: [.NetCore]

---

# ExceptionMiddleware => 遇到問題就來寫 Log 吧
###### tags: `.NetCore`

## ExceptionMiddleware
```
public class ExceptionMiddleware {
    private readonly RequestDelegate _next;
    private readonly ILogger<ExceptionMiddleware> _logger;
    public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger) {
        _logger = logger;
        _next = next;
    }

    public async Task Invoke(HttpContext context) {

        RequestErrorResult errorResult = null;
        var errorHttpCode = (int)HttpStatusCode.OK;

        try {
            await _next(context);
        }

        catch (Exception exception) {
            switch (exception) {
                case RequestException requestException:
                    errorHttpCode = (int)requestException.StatusCode;
                    errorResult = new RequestErrorResult(ERequestErrorType.Request, exception.Message);
                    break;
                default:
                    errorHttpCode = (int)HttpStatusCode.InternalServerError;
                    errorResult = new RequestErrorResult(ERequestErrorType.Unknow, exception.ToString());
                    break;
            }
        }

        if (errorResult == null)
            return;

        else {
            _logger.LogError(JsonConvert.SerializeObject(new {
                FullUrl = context.Request.GetDisplayUrl(), // 完整的網址列
                Error = errorResult, // 錯誤內容
            }, Formatting.Indented));

            // return the error to client.
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = errorHttpCode;
            await context.Response.WriteAsync(JsonConvert.SerializeObject(errorResult));
        }
    }
    }
```

## 在 StartUp.cs > public void Configure 中設定 Router 必經 ExceptionMiddleware
```
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ICommonHttpContext commonHttpContext) {
        // Regist Exception Middleware (Handle the all exception of this website)
        app.UseMiddleware<ExceptionMiddleware>();

        if (env.IsDevelopment()) {
            app.UseSwagger();
            app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "dataApi v1"));
        }

        // 建立專案的時候勾選了 https，但不需要這個，自己把憑證設好
        //app.UseHttpsRedirection();
        app.UseRouting();

        // 使用定義在 ConfigureServices 的 CORS 設定 ( ※一定要配置在 Routing 後面 )
        app.UseCors("CorsPolicy");

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints => {
            endpoints.MapControllers();
        });
    }
}
```