如何获取从 .NET catch 到 React.JS 的错误详细信息?

How to get details of error from .NET catch to React.JS?

我的 Api 服务在 .NET 中,我的客户端在 React.js 中。我使用 axios.post 从 .NET 发送参数和检索数据。当服务端发生某些事情时,我想在 react.js 端查看错误详细信息。示例代码如下;

[HttpPost]
    public ConcreteAccrument CalculateDepositAmount([FromBody] DepositAmountParameters depositAmountParameters)
    {
        ConcreteApplication application = depositAmountParameters.application;
        int multiplier = depositAmountParameters.multiplier;
        bool forceCalculation = depositAmountParameters.forceCalculation;
        long registryInfoOid = depositAmountParameters.registryInfoOid;
        long subscriberRegistryOid = depositAmountParameters.subscriberRegistryOid;

        try
        {
            Com.BS.WaterSupplyAndSeverage.Services.WaterSupplyAndSewerage wssService = new Com.BS.WaterSupplyAndSeverage.Services.WaterSupplyAndSewerage();
            return wssService.CalculateDepositAmount(application, multiplier, forceCalculation, registryInfoOid, subscriberRegistryOid);
        }
        catch (BSException e)
        {
            FileLogger.Error(CLASS_NAME, "CalculateDepositAmount", e.Message, e.StackTrace, application, multiplier, forceCalculation);
            BSCommunicationException commException = new BSCommunicationException();
            commException.Id = e.Id;
            commException.ExceptionMessage = e.ExceptionMessage;
            throw new FaultException<BSCommunicationException>(commException, new FaultReason(commException.ExceptionMessage));
        }
        catch (Exception e)
        {
            FileLogger.Error(CLASS_NAME, "CalculateDepositAmount", e.Message, e.StackTrace, application, multiplier, forceCalculation);
            BSCommunicationException commException = PrepareCommunicationException(e);
            throw new FaultException<BSCommunicationException>(commException, new FaultReason(commException.ExceptionMessage));
        }
    }

throw new FaultException at first catch(BSException e)中有一些细节。这不是系统错误。例如,当 first catch 工作时,数据为空或某些值丢失。第二个问题是系统错误。但是在该代码中,所有代码都在 React.Js 端捕获 return 500 错误。我想要的只是在 React.js 端查看 first catch 中的所有细节。当我在 catch 中使用“return 错误”时,我得到转换错误,因为我的 class return 一个对象。

这是我的 react.js 代码;

export const CalculateDepositAmount = (APPLICATION,MULTIPLIER,FORCE_CALCULATION,REGISTRY_INFO_OID, SUBSCRIBER_REGISTRY_OID, SuccessOperation, FailedOperation) => {
return () => {

const body = { application:APPLICATION,multiplier:MULTIPLIER,forceCalculation:FORCE_CALCULATION,registryInfoOid:REGISTRY_INFO_OID, subscriberRegistryOid:SUBSCRIBER_REGISTRY_OID};
console.log("bodyFormData",body)
axios.post('https://localhost:44396/api/CalculateDepositAmount', body)
  .then( async response => {
    SuccessOperation({ CALCULATED_DEPOSIT_AMOUNT_DATA: await response.data });
  })
  .catch(() => {
    FailedOperation({ CALCULATED_DEPOSIT_AMOUNT_DATA: null })
  });
  }
}

我假设这不是 asp.net core / 5 / 6,而是 vanilla 4.x

您可以做的一件事是将方法签名更改为 IHttpActionResult,这样您就可以 return 不同的状态代码,将不同的有效负载返回给客户端:

public IHttpActionResult CalculateDepositAmount([FromBody] DepositAmountParameters depositAmountParameters) 
{
    try
    { 
       var result = wssService.CalculateDepositAmount(application, multiplier, forceCalculation, registryInfoOid, subscriberRegistryOid);
       return Ok(result);
    }
    catch (BSException e)
    {
        return BadRequest(e.Message)
        //or
        //return StatusCode(418)
    }
    catch (Exception e)
    {
        
    }
}

您可以根据自己的需要更好地调整对客户端的响应,而不是 return 对象或异常。您可以在此处找到完整列表:

https://docs.microsoft.com/en-us/previous-versions/aspnet/dn314678(v=vs.118)?redirectedfrom=MSDN

另一种需要更多重构的方法是将服务的 return 类型更改为某种 Result 对象,这表明它是成功的操作还是出现问题。

例如,以这个 CommandResult 为例:

public class CommandResult<T>
{
    private CommandResult(T payload) => Payload = payload;

    private CommandResult(string failureReason)
    {
        FailureReason = failureReason;
    }

    public string FailureReason { get; }
    public string Message { get; }
    public bool IsSuccess => string.IsNullOrEmpty(FailureReason);

    public T Payload { get; }

    public static implicit operator bool(CommandResult<T> result) => result.IsSuccess;

    public static CommandResult<T> Success(T payload)
        => new(payload);

    public static CommandResult<T> Fail(string reason)
        => new(reason);
}

在您的服务中,您现在可以执行以下操作:

public Commandresult<ConcreteAccrument> CalculateDepositAmount(DepositAmountParameters depositAmountParameters) 
{
    try
    { 
       var result = // do the calculation
       return CommandResult<ConcreteAccrument>.Success(result);
    }
    catch (BSException e)
    {
        return CommandResult<ConcreteAccrument>.Fail(e.Message);
    }
    catch (Exception e)
    {
        return CommandResult<ConcreteAccrument>.Fail(e.Message);
    }
}

现在您的控制器只需决定是否成功:

public IHttpActionResult CalculateDepositAmount([FromBody] DepositAmountParameters depositAmountParameters) 
{
    
   var result = wssService.CalculateDepositAmount(application, multiplier, forceCalculation, registryInfoOid, subscriberRegistryOid);
   if(result.IsSuccess)  // or simply if (result)
   {
       return Ok(result.Payload);
   }
   return Exception(result.FailureReason); //or whatever suits best.  
}