.net 核心从存储库中抛出 badrequest

.net core throw badrequest from repository

目前在存储库中会抛出一些 ArgumentException,即当所选代码已在使用时。

public DM.Category Add(DM.Category category)
    {
        if (_context.Categories.Any(x => x.Code == category.Code))
        {
            throw new ArgumentException($"Category code '{category.Code}' already in use");
        }

        return _context.Categories.Add(category).Entity;
    }

现在,如果发生这种情况,所有用户在控制台中看到的都是 500。我怎样才能巧妙地将此错误抛给 UI (angular) / 最佳做法是什么?

我看了

[HttpPost("[action]")]
public IActionResult test(Option option)
{
    return BadRequest("Error message here");
}

但我无法在我的存储库(继承自 BaseRepository)中使用它。

ASP.NET Core 提供了 ProblemDetails class 和 ValidationProblemDetails 来处理 HTTP 错误的详细信息基于 RFC 7807 的响应

您可以在此处阅读规范 https://www.rfc-editor.org/rfc/rfc7807

在您的情况下,您可能想要创建一个中间件来捕获您的自定义异常和 return ProblemDetails

会是这样的

public class CustomExceptionHandlerMiddleware
    {
        private readonly RequestDelegate next;
        private readonly IHostEnvironment host;

        public CustomExceptionHandlerMiddleware(RequestDelegate next, IHostEnvironment host)
        {
            this.next = next;
            this.host = host;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                var body = context.Response.StatusCode;
                await next(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var problemDetail = new ProblemDetails()
            {
                Title = exception.Message,
                Detail = exception.StackTrace,
                Instance = context.Request.Path,
                Status = StatusCodes.Status500InternalServerError,
            };

            // for security reason, not leaking any implementation/error detail in production
            if (host.IsProduction())
            {
                problemDetail.Detail = "Unexpected error occured";
            }

            context.Response.StatusCode = StatusCodes.Status500InternalServerError;
            context.Response.ContentType = "applications/problem+json";

            return context.Response.WriteAsync(JsonConvert.SerializeObject(problemDetail));
        }
    }