我有一个中央应用程序,它通过控制器与多个其他应用程序通信。 假设控制器 A(源)向控制器 B 寻求一些数据。目前,我们返回数据,并且仅返回数据(没有时间戳,没有用户详细信息等)
应用程序1:控制器A
public async Task<ActionResult<ExpectedType>> GetData(ModelType model)
{
try
{
var response = await _dataFetchingBizLayer.GetThatDataFromApp2(model);
return response;
}
catch (Exception ex)
{
_logger.Log(ex);
return StatusCode(500, ex.Message); // "There was an issue."
}
}
应用程序1:_dataFetchingBizLayer(业务逻辑层)
public async Task<ExpectedType> GetThatDataFromApp2(ModelType model)
{
var response = await _secondaryAppWrapper.GetThatData(
new QueryModelType
{
//... shape the query data object
});
return response;
}
应用程序2:控制器B
public ActionResult<ExpectedType> GetThatData(QueryModelType model)
{
try
{
var response = _dataFetchingDAO.GetDataFromDB(model);
return response;
}
catch (CustomException customEx)
{
_logger.Log(customEx);
return StatusCode(500, customEx.Message); // "The error occurred at station B."
}
}
话虽如此,控制器 B 已编写为包含一些自定义异常,这些异常在适用的系统各个部分中抛出。 不幸的是,当控制器 B 中抛出自定义异常并返回时,控制器 A 中看到的异常不包含该自定义消息。相反,它输出自己的消息,如上所示。
我可以通过在控制器 A 中使用
APIException
来捕获控制器 B 引发的异常来找到解决方法。我还必须更新控制器 B 的返回值以返回 ex.Response
而不是 ex.Message
。
在控制器 A 中:
catch (APIException apiEx)
{
_logger.Log(apiEx);
return StatusCode(500, apiEx.Response);
}
我想知道是否有办法传输自定义消息和状态代码,以及捕获从控制器 B 发送到控制器 A 的其他异常类型。
我不确定这是否是一个长期可行的解决方案,我目前正在考虑创建自定义响应类作为更好的解决方案。
如果需要任何其他信息,请告诉我。
您可以直接在控制器 A 中进行此调用 _dataFetchingBizLogic.GetDataFromDB(model);,然后也在控制器 A 中捕获 CustomException。
考虑不要将控制器相互耦合,这是一个糟糕的设计。