【问题标题】:How should I return errors in asp .net core API我应该如何在 asp .net core API 中返回错误
【发布时间】:2021-07-13 17:24:34
【问题描述】:

我正在使用 .Net Core 和 Angular 处理我的私人项目,但我对如何返回错误有点困惑。

我的后端有层(控制器、服务、存储库和实体)。 我已经创建了我想要返回的一般响应对象。在我的服务方法中,我将不同的错误设置为 StatusCode,例如“NotFound”或“Internal server error”。

我不想在 StatusCode 上切换大小写并根据控制器中的错误返回不同的错误,因为我认为这不是一个好的解决方案。 返回 ApiResponse 对象将导致我总是有 200 个代码,并且要知道是否有任何错误,我需要检查 Angular 中返回对象的状态代码。我不知道这是否是一个好的解决方案。

我想保留这些图层。我希望控制器只处理请求,服务拥有所有逻辑和存储库来执行 CRUD 操作。

那么我应该如何将错误从我的服务层返回到控制器?

这是我的控制器方法的一个版本。

    [Authorize]
    [ApiValidationFilter]
    [HttpPost("updateFacebookUrl/")]
    public async Task<ApiResponse> UpdateFacebookURL([FromBody] UpdateURLVm updateURLVm)
    {
      return await _userInfoService.UpdateFacebookURL(updateURLVm);
    }

这是我的控制器方法的第二个版本。

    [Authorize]
    [ApiValidationFilter]
    [HttpPost("updateInstagramUrl/")]
    public async Task<IActionResult> UpdateInstagramURL([FromBody] UpdateURLVm updateURLVm)
    {
      var result = await _userInfoService.UpdateInstagramURL(updateURLVm);

      if (result.StatusCode != (int)HttpStatusCode.OK)
      {
        return BadRequest(result);
      }

      return Ok(result);
    }

这是我的服务方式。

    public ApiResponse UpdateInstagramURL(UpdateURLVm updateURLVm)
    {
      try
      {
        var user = _unitOfWork.userRepository.FindByCondition(x => x.Id == updateURLVm.UserId).FirstOrDefault();

        if (user == null)
          return new ApiResponse((int)HttpStatusCode.NotFound, "User not found");

        user.Instagram = updateURLVm.URL;

        _unitOfWork.userRepository.Update(user);
        _unitOfWork.Complete();

        return new ApiResponse((int)HttpStatusCode.OK);
      }
      catch (Exception ex)
      {
        return new ApiResponse((int)HttpStatusCode.InternalServerError, "Something went wrong");
      }
    }

返回对象。

 public class ApiResponse
  {
    public int StatusCode { get; private set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
    public string Message { get; private set; }

    [JsonProperty(DefaultValueHandling = DefaultValueHandling.Ignore)]
    public object Result { get; private set; }

    public ApiResponse(int statusCode, string message)
        : this(statusCode)
    {
      this.Message = message;
    }

    public ApiResponse(object result) :
      this(200)
    {
      Result = result;
    }

    public ApiResponse(int statusCode)
    {
      this.StatusCode = statusCode;
    }
  }

【问题讨论】:

  • 我想说你可以尝试引入一些中间件/OnActionExecuted 动作过滤器来分析 IActionResult 并设置有效状态。
  • 谢谢,我会研究那个解决方案。
  • 是的,我过去使用过中间件,我会发布我的示例

标签: angular asp.net-core


【解决方案1】:

我会在我的核心服务或存储库中抛出异常并让中间件处理它。 ApiError 是我的自定义类,有些东西可能与使用 .NET Core 2.2 编写的不同,我想您使用的是 3.x。还有一个简短的说明(如果可以的话)那些 api 端点 url 不是很 RESTful..

   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseExceptionHandler(appBuilder =>
        {
            appBuilder.Run(async context => {
                var ex = context.Features.Get<IExceptionHandlerPathFeature>();
                if (ex?.Error is NullReferenceException)
                    context.Response.StatusCode = 404;
                else if (ex?.Error is InvalidOperationException)
                    context.Response.StatusCode = 400;
                else
                    context.Response.StatusCode = 500;

                context.Response.ContentType = "application/json";

                ApiError error = new ApiError()
                {
                    Code = context.Response.StatusCode,
                    Message = env.IsDevelopment() ? ex?.Error.Message : "An unexpected error happened. Try again later."
                };

                await context.Response.WriteAsync(JsonConvert.SerializeObject(error)).ConfigureAwait(false);
            });
        });
   }

【讨论】:

  • 非常感谢。这正是我一直在寻找的。至于端点,我现在正在重组我的整个后端。这个项目是我的文凭项目,现在我想继续这个项目,但我正在尝试使用更多的设计模式、更好的技术、解决方案等。我希望这个项目成为求职面试或其他东西的“炫耀”项目:)。我想在工作的同时尽可能多地学习。
猜你喜欢
  • 2020-06-03
  • 2021-09-03
  • 2021-03-04
  • 2020-09-07
  • 1970-01-01
  • 2020-06-04
  • 2020-03-07
  • 2018-04-12
  • 2021-03-25
相关资源
最近更新 更多