Skip to content

Commit 6d4947d

Browse files
author
Vadim Belov
committed
Refactor WebApiException error model construction
Refactored GetErrorModel() to build ErrorModel directly, replacing ProblemDetails usage. Added GetRfcType() to map status codes to RFC URLs and used ReasonPhrases.GetReasonPhrase for error titles. Updated traceId handling and removed dependency on Microsoft.AspNetCore.Mvc in favor of Microsoft.AspNetCore.WebUtilities.
1 parent 84adbf4 commit 6d4947d

1 file changed

Lines changed: 21 additions & 16 deletions

File tree

Sources/EasyExtensions.AspNetCore/Exceptions/WebApiException.cs

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
using EasyExtensions.Abstractions;
55
using EasyExtensions.Models;
6-
using Microsoft.AspNetCore.Mvc;
6+
using Microsoft.AspNetCore.WebUtilities;
77
using System;
88
using System.Collections.Generic;
99
using System.Diagnostics;
@@ -53,28 +53,33 @@ public class WebApiException(
5353
/// <returns> Error model. </returns>
5454
public ErrorModel GetErrorModel()
5555
{
56-
ProblemDetails details = new ProblemDetails()
57-
{
58-
Status = (int)StatusCode,
59-
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
60-
Title = "Web API actions errors occurred.",
61-
};
62-
string? traceId = Activity.Current?.Id ?? "-";
63-
if (!string.IsNullOrWhiteSpace(traceId))
64-
{
65-
details.Extensions["traceId"] = traceId;
66-
}
56+
int statusCode = (int)StatusCode;
6757
return new()
6858
{
69-
Status = (int)StatusCode,
70-
Type = "https://tools.ietf.org/html/rfc7231#section-6.5.1",
71-
Title = "Web API actions errors occurred.",
72-
TraceId = Activity.Current?.Id ?? "-",
59+
Status = statusCode,
60+
Type = GetRfcType(StatusCode),
61+
Title = ReasonPhrases.GetReasonPhrase(statusCode),
62+
TraceId = Activity.Current?.Id ?? string.Empty,
7363
Errors = new Dictionary<string, string>
7464
{
7565
{ ObjectName, Message }
7666
}
7767
};
7868
}
69+
70+
private static string GetRfcType(HttpStatusCode statusCode)
71+
=> statusCode switch
72+
{
73+
HttpStatusCode.BadRequest => "https://tools.ietf.org/html/rfc7231#section-6.5.1",
74+
HttpStatusCode.Unauthorized => "https://tools.ietf.org/html/rfc7235#section-3.1",
75+
HttpStatusCode.Forbidden => "https://tools.ietf.org/html/rfc7231#section-6.5.3",
76+
HttpStatusCode.NotFound => "https://tools.ietf.org/html/rfc7231#section-6.5.4",
77+
HttpStatusCode.Conflict => "https://tools.ietf.org/html/rfc7231#section-6.5.8",
78+
HttpStatusCode.UnprocessableEntity => "https://tools.ietf.org/html/rfc4918#section-11.2",
79+
HttpStatusCode.TooManyRequests => "https://tools.ietf.org/html/rfc6585#section-4",
80+
HttpStatusCode.InternalServerError => "https://tools.ietf.org/html/rfc7231#section-6.6.1",
81+
HttpStatusCode.ServiceUnavailable => "https://tools.ietf.org/html/rfc7231#section-6.6.4",
82+
_ => "https://tools.ietf.org/html/rfc7231"
83+
};
7984
}
8085
}

0 commit comments

Comments
 (0)