使用API 时正确的错误处理方式?

问题描述 投票:2回答:1

我对处理来自桌面应用程序的API请求时的一般错误处理流程有疑问。我将此代码放在其自己的帮助器类中,并返回到我的桌面应用程序中View的代码隐藏(即,从中调用此设置的View代码)。设计此帮助器类以在其中捕获可能的异常并返回到父调用,或直接从顶层进行处理时,是最好的方法吗?

来自代码隐藏类的调用是:

 try
        {
            // other stuff here for access tokens
            await GraphService.GetMyEventsAsync();
        }
catch (ServiceException ex)
        {
            if (ex.StatusCode == System.Net.HttpStatusCode.Unauthorized)
            {
                // MS Graph Known Error 
                // Users need to sign into OneDrive at least once
                // https://docs.microsoft.com/en-us/graph/known-issues#files-onedrive

                // Empty all cached accounts / data to allow user to rety
                await authProvider.SignOut();

                await DisplayMessageAsync("Error 401. Access Denied. Please make sure you've logged\ninto OneDrive and your email at least once then try again.");
            }
            else if (ex.StatusCode == HttpStatusCode.NotFound)
            {
                await DisplayMessageAsync("Error 404. Resource requested is not available.");
            }
            else if (ex.StatusCode == HttpStatusCode.ServiceUnavailable)
            {
                await DisplayMessageAsync("Error 503. Service unavailable due to high load or maintenance.\nPlease try again in a few.");
            }
            else if (ex.StatusCode == HttpStatusCode.Conflict)
            {
                await DisplayMessageAsync("Error 409. Error backing up, issue retrieving backup folder. Please try again.");
            }
        }

这是来自帮助器类的:

 public static async Task<IEnumerable<Event>> GetEventsAsync()
    {
        try
        {
            // GET /me/events
            var resultPage = await GraphClient.Me.Events.Request()
                // Only return the fields used by the application
                .Select(e => new {
                    e.Subject,
                    e.Organizer,
                    e.Start,
                    e.End
                })
                // Sort results by when they were created, newest first
                .OrderBy("createdDateTime DESC")
                .GetAsync();

            return resultPage.CurrentPage;
        }
        catch (ServiceException ex)
        {
            // throw here or handle error certain 400-500 http error codes here and throw?
            Console.WriteLine($"Service Exception, Error getting events: {ex.Message}");
            return null;
        }
    }
c# .net office365api
1个回答
0
投票

为了能够成功处理API响应状态的错误和成功检查。它可以告诉您很多有关API流程和状态的信息。

REST API-响应代码和状态。http://developer.commvault.com/commvault/v11/article?p=45599.htm

© www.soinside.com 2019 - 2024. All rights reserved.