如果返回某个错误代码,请重新向Web服务发送请求

本文关键字:Web 服务 请求 返回 错误代码 如果 | 更新日期: 2023-09-27 17:58:37

在我的应用程序中发生的第一个调用是对web服务的Login()请求,该请求返回将用于所有未来调用的会话ID。但是,经过足够长的时间后,会话ID可能会变得无效。所以,我的电话是这样的:

UserService.Status request = serviceInstance.doSomething(id, out result)
// If the error is for an invalid sessionID, log in again
if (request.ErrorCode == 1) { login(); }

这很好,但在执行刷新之前,页面仍将在没有任何来自Web服务的详细信息的情况下加载。这里的简单解决方案是将serviceInstance.doSomething()粘贴到条件中,但如果有50多个Web服务方法,则意味着将相同的代码复制50多次。有没有一种聪明的方法可以绕过这一点,并在出现任何UserService.Status.Errorcode == 1情况时重新执行请求?

如果它是相关的,Status对象看起来像:

<s:complexType name="Status">
    <s:attribute name="Status" type="tns:ReMAEStatusType" use="required" />
    <s:attribute name="Source" type="s:string" />
    <s:attribute name="Message" type="s:string" />
    <s:attribute name="StackTrace" type="s:string" />
    <s:attribute name="ErrorCode" type="s:int" />
</s:complexType>

如果返回某个错误代码,请重新向Web服务发送请求

我最终使用了结合反射的重试逻辑。这里的想法是能够为每个WebService方法处理一个错误,而无需在每个调用中重复try-catch循环。

// Make up to two attempts at the Try block
for (int i = 0; i < 2; i++)
{
    try
    {
        // Invoke some web service method that returns error codes but not exceptions here... I used reflection
        Service.Status request = (Service.Status)typeof(WebService).GetMethod(someString).Invoke(someWebServiceInstance, someArgs);
        if (request.ErrorCode == 0)
        {
            // No errors! Do some stuff. Return a value. Make sure to get out of the loop
            return request.Message;
        }
        else
        {
            // Log some stuff if there was an error...
            Debug.WriteLine("Error Code: " + request.ErrorCode + "'nMessage: " + request.Message);
            // Start handling individual error codes as needed
            if (request.ErrorCode == 1)
            {
                // Seems the session ID is invalid!
                throw new UnauthorizedAccessException(request.Message);
            }
            else
            {
                // Throw some other exceptions....
                // If they can't be handled, make sure to break the loop in the catch block
            }
        }
    }
    catch (UnauthorizedAccessException)
    {
        // Start catching our exceptions. Lets get a new Session ID, and since we didn't return anything
        // The loop will let us give the try block another shot
        login();
    }