。net核心从存储库抛出badrequest

问题描述 投票:0回答:1

目前,在存储库中,引发了一些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(角度)/最佳实践是什么?

我看过

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

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

.net asp.net-core exception bad-request
1个回答
0
投票

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

您可以在https://tools.ietf.org/html/rfc7807处阅读规格

在您的情况下,您可能想要创建一个捕获自定义异常并返回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));
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.