EF异常统一处理

来源:3-6 【应用】创建数据库

慕莱坞5376718

2021-04-15

老师你好,请教下,如何把下面错误信息
{
“errors”: {
“userName”: [
“The field UserName must be a string or array type with a maximum length of ‘30’.”
]
},
“type”: “https://tools.ietf.org/html/rfc7231#section-6.5.1”,
“title”: “One or more validation errors occurred.”,
“status”: 400,
“traceId”: “00-173c342f3b72f34c9bf8c01313bdaf17-c08ca39808a3034b-00”
}

统一格式化成
{
“status”: 400,
“msg”: “操作失败!”,
“data”: [
{
“errors”: {
“userName”: [
“The field UserName must be a string or array type with a maximum length of ‘30’.”
]
},
“type”: “https://tools.ietf.org/html/rfc7231#section-6.5.1”,
“title”: “One or more validation errors occurred.”,
“status”: 400,
“traceId”: “00-173c342f3b72f34c9bf8c01313bdaf17-c08ca39808a3034b-00”
}
]
}

写回答

1回答

阿莱克斯刘

2024-09-27

你好!你可以通过自定义中间件或在控制器中手动处理错误响应来实现错误信息的统一格式化。以下是一个示例,展示如何在 ASP.NET Core 中实现这一点:

自定义中间件
首先,创建一个自定义中间件来捕获和格式化错误响应。

ErrorHandlingMiddleware.cs
public class ErrorHandlingMiddleware
{
    private readonly RequestDelegate _next;

    public ErrorHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex);
        }
    }

    private static Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        var code = HttpStatusCode.InternalServerError; // 500 if unexpected

        var result = JsonConvert.SerializeObject(new
        {
            status = (int)code,
            msg = "操作失败!",
            data = new[]
            {
                new
                {
                    errors = new Dictionary<string, string[]>
                    {
                        { "Exception", new[] { exception.Message } }
                    },
                    type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
                    title = "One or more validation errors occurred.",
                    status = (int)code,
                    traceId = context.TraceIdentifier
                }
            }
        });
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)code;
        return context.Response.WriteAsync(result);
    }
}
0
0

.Net 开发电商后端API 从0到精通RESTful

. Net 实战+RESTful思想纵深课程,开发优雅RESTful风格API。

977 学习 · 547 问题

查看课程