net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)四全局异常处理
Posted 圆滚滚的胖狸
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)四全局异常处理相关的知识,希望对你有一定的参考价值。
首先创建一个返回值模型类,在IRepository项目里创建接口,在Repository项目里创建实体类,这样做是为了能够直接实现依赖注入
namespace NET6Demo.IRepository //注意这里的命名空间,并没有Utilities
public interface IResultModel
int StatusCode get; set;
string? Message get; set;
object? Result get; set;
using NET6Demo.Interface.Dependency;
using NET6Demo.IRepository;
namespace NET6Demo.Repository //注意这里的命名空间,并没有Utilities
public class ResultModel : IResultModel, IDependency
public int StatusCode get; set;
public string? Message get; set; = String.Empty;
public object? Result get; set; = null;
在Utility项目中建立异常处理中间件
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NET6Demo.IRepository;
using System.Text.Json;
namespace NET6Demo.Utility.ErrorHandler
public class ExceptionHandlingMiddleware
private readonly RequestDelegate _next; // 用来处理上下文请求
private readonly ILogger<ExceptionHandlingMiddleware> _logger;
private IResultModel errorResponse;
public ExceptionHandlingMiddleware(
RequestDelegate next,
ILogger<ExceptionHandlingMiddleware> logger,
IResultModel result
)
_next = next;
_logger = logger;
errorResponse = result;
public async Task InvokeAsync(HttpContext httpContext)
try
await _next(httpContext); //要么在中间件中处理,要么被传递到下一个中间件中去
catch (Exception ex)
await HandleExceptionAsync(httpContext, ex); // 捕获异常了 在HandleExceptionAsync中处理
private async Task HandleExceptionAsync(HttpContext context, Exception exception)
//errorResponse = new ResultModel();
_logger.LogError(exception.Message);
context.Response.ContentType = "application/json"; // 返回json 类型
var response = context.Response;
switch (exception)
case ApplicationException ex:
if (ex.Message.Contains("Invalid token"))
response.StatusCode = errorResponse.StatusCode = StatusCodes.Status403Forbidden;
errorResponse.Message = "Invalid token";
break;
response.StatusCode = errorResponse.StatusCode = StatusCodes.Status400BadRequest;
errorResponse.Message = ex.Message;
break;
case KeyNotFoundException ex:
response.StatusCode = errorResponse.StatusCode = StatusCodes.Status404NotFound;
errorResponse.Message = ex.Message;
break;
default:
response.StatusCode = errorResponse.StatusCode = StatusCodes.Status500InternalServerError;
errorResponse.Message = "Internal Server errors. Check Logs!";
break;
_logger.LogError(exception.Message);
var result = JsonSerializer.Serialize(errorResponse);
await context.Response.WriteAsync(result);
在program.cs中添加中间件引用
#region 统一异常处理
app.UseMiddleware<ExceptionHandlingMiddleware>();
#endregion
修改TestController中的代码,来测试一下
[HttpGet("GetTest")]
public async Task<IActionResult> GetTestResult(string userId)
Console.WriteLine("测试一下输出日志");
_logger.LogInformation("日志输出了");
_user = _provider.GetService<IUsers>().GetUser(userId);
throw new Exception("Test exception");
//return Ok(_user);
运行起来,在swagger中测试GetTest。
可以看到API返回了我们自定义的结果。同时项目的bin文件夹中,也产生的相应的错误日志
以上是关于net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)四全局异常处理的主要内容,如果未能解决你的问题,请参考以下文章
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)二配置log4net
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)六添加身份验证,引入JWT
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)六添加身份验证,引入JWT
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)六添加身份验证,引入JWT
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)一建立项目,使用Swagger
net6 项目搭建及引用框架记录(log4net,autofac,exception,api result,jwt,efcore)一建立项目,使用Swagger