Skip to content

Commit

Permalink
AuthorizationFormHtmlParser: улучшить обработку ошибок
Browse files Browse the repository at this point in the history
  • Loading branch information
itsokto committed May 23, 2020
1 parent b7dd567 commit 94a153c
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using JetBrains.Annotations;
using VkNet.Abstractions.Utils;
using VkNet.Exception;
using VkNet.Model;
using VkNet.Utils;

namespace VkNet.Infrastructure.Authorization.ImplicitFlow
Expand All @@ -30,6 +31,16 @@ public async Task<VkHtmlFormResult> GetFormAsync(Uri url)
{
var response = await _restClient.PostAsync(url, Enumerable.Empty<KeyValuePair<string, string>>());

if (!response.IsSuccess)
{
throw new VkAuthorizationException(response.Message);
}

if (Utilities.TryDeserializeObject<VkAuthError>(response.Value, out var authError))
{
throw new VkAuthorizationException(authError.ErrorDescription);
}

var doc = new HtmlDocument();
doc.LoadHtml(response.Value);
var formNode = GetFormNode(doc);
Expand Down
42 changes: 42 additions & 0 deletions VkNet/Model/VkAuthError.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
using System;
using Newtonsoft.Json;

namespace VkNet.Model
{
/// <summary>
/// Authorization error.
/// </summary>
[Serializable]
public class VkAuthError
{
/// <summary>
/// Error.
/// </summary>
[JsonProperty("error")]
public string Error { get; set; }

/// <summary>
/// Error type.
/// </summary>
[JsonProperty("error_type")]
public string ErrorType { get; set; }

/// <summary>
/// Error description.
/// </summary>
[JsonProperty("error_description")]
public string ErrorDescription { get; set; }

/// <summary>
/// Captcha id.
/// </summary>
[JsonProperty("captcha_sid")]
public ulong? CaptchaSid { get; set; }

/// <summary>
/// Captcha image Uri.
/// </summary>
[JsonProperty("captcha_img")]
public Uri CaptchaImg { get; set; }
}
}
21 changes: 21 additions & 0 deletions VkNet/Utils/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,5 +118,26 @@ public static string SerializeToJson<T>(T @object)

return result == "null" ? null : result;
}

/// <summary>
/// Deserializes JSON for the specified .NET type. A return value indicates whether deserialization succeeded.
/// </summary>
/// <param name="json"> The JSON to deserialize. </param>
/// <param name="result"> Deserialized object. </param>
/// <typeparam name="T"> Type for deserialization. </typeparam>
/// <returns></returns>
public static bool TryDeserializeObject<T>(string json, out T result)
{
try
{
result = JsonConvert.DeserializeObject<T>(json);
return true;
}
catch
{
result = default;
return false;
}
}
}
}

0 comments on commit 94a153c

Please sign in to comment.