【问题标题】:How to return error message from service to controller and then to client如何将错误消息从服务返回到控制器,然后返回到客户端
【发布时间】:2021-08-27 05:23:06
【问题描述】:

例如,当元素为 null 时,如何将错误消息从 service.cs 返回到控制器,然后返回到客户端(Angular)? 返回服务器端出现问题的信息的正确方法是什么?我只想在例如元素为空时返回 ex.Message 或带有信息的字符串。

角度

 getTree(id: number) {
    return this.http.get<any>(this.baseURL + 'home/Tree/' + id)
      .pipe(
        retry(0),
        catchError(this.errorHandler)
      );
  }




errorHandler(error) {
    let errorMessage = '';
    if (error.error instanceof ErrorEvent) {
      // Get client-side error
      errorMessage = error.error.message;
    } else {
      // Get server-side error
      errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
    }
    console.log(errorMessage);
    return throwError(errorMessage);
  }

控制器

 [HttpGet]
 [Route("Tree/{elementId}")]
 public FoodNode Tree(int elementId)
    {
        try
        {
            var json = _service.GetConnectionsForId(elementId);

            return json;
        }
        catch (Exception ex)
        {

            throw;
        }
    }

Service.cs

  public ElementNode GetConnectionsForId(int id)
    {
        try
        {
            string message;

            Element element = _context.Elements.Find(id);
         }
         catch(Exception ex){
           return ex.Message;
         }

【问题讨论】:

  • 为什么要使用异常来处理已知的失败案例?
  • ASP.NET 核心?也许这可以帮助:Controller action return types
  • @Llama 我应该使用 onlu if(element !=null) 或类似的东西吗?
  • 是的,这将是一种更好的处理方式。如果元素是null,我不明白为什么GetConnectionsForId 不简单地返回null。
  • 哦,好的,谢谢。我认为这是告诉用户服务器端出了什么问题的更好方式

标签: c# angular typescript .net-core error-handling


【解决方案1】:

从你的服务中抛出一个NoConnectionException:

public ElementNode GetConnectionsForId(int id)
{
    try
    {
        string message;
        Element element = _context.Elements.Find(id);
    }
    catch(Exception ex)
    {
        throw new NoConnectionException(ex);
    }
}

public class NoConnectionException : Exception
{
    public NoConnectionException(Exception inner) : base(inner)
    {
    }
}

在你的控制器中捕获NoConnectionException:

[HttpGet]
[Route("Tree/{elementId}")]
public ActionResult<FoodNode> Tree2(int elementId)
{
    try
    {
        var json = _service.GetConnectionsForId(elementId);
        return Ok(json);
    }
    // Beware: Give all the exceptions in your try-clause a unique name, otherwise they'll be null
    catch (NoConnectionException noConnEx)
    {
        return StatusCode(501); // Or whatever status code you want to assign to this
    }
    catch (Exception ex)
    {
        return StatusCode(500);
    }
}

并在您的角度服务中处理状态码:

getTree(id: number) {
  return this.http.get<any>(this.baseURL + 'home/Tree/' + id)
    .pipe(
      retry(0),
      catchError(this.errorHandler) // <-- I assume the error handler will pass you the status code so here you can look for 500 or 501 or ...
    );
}

【讨论】:

  • 谢谢。我在客户端收到错误,但没有来自服务的消息。
  • 从 ASP.NET Core 应用程序/DbContext 传递内部错误消息通常不是最好的主意。此外,您很可能想要翻译错误消息。这通常在您根据 httpStatusCode 选择翻译的客户端完成。但是,如果你真的想要,你可以从 MVC 控制器返回一个 JsonResponse。
  • 哦,我现在明白了,我忘记了return。我把它改成return StatusCode(500);
  • 嗯,我怎么能告诉用户这个项目不存在呢?创建一个新的客户端和服务器端方法来检查这个?
  • return NotFound(); 来自您的控制器方法
猜你喜欢
  • 1970-01-01
  • 2021-01-26
  • 2011-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多