如何 return 从服务到控制器再到客户端的错误消息

How to return error message from service to controller and then to client

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

Angular

 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;
         }

从您的服务中抛出 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);
    }
}

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

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 ...
    );
}