Похожие чаты

Foundation controler protected async Task<IActionResult> ExecuteActionAsync<T>(Func<Task<(int statusCode, T result, string

message)>> action, string methodName)
{
var stopwatch = Stopwatch.StartNew();
var request = _httpContextAccessor.HttpContext.Request;
var user = _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated
? _httpContextAccessor.HttpContext.User.Identity.Name
: "Anonymous";

try
{
var (statusCode, result, message) = await action();
return AcResponse(statusCode, message, result);
}
catch (Exception ex)
{
_logger.LogError(ex, "An error occurred in {MethodName}. User: {User}. URL: {Url}. Query: {Query}",
methodName, user, request.Path, request.QueryString);
return AcResponse(500, "An error occurred while processing your request.", default(T), new List<string> { ex.Message });
}
finally
{
stopwatch.Stop();
_logger.LogInformation("{MethodName} executed in {Duration} ms. User: {User}. URL: {Url}. Query: {Query}",
methodName, stopwatch.ElapsedMilliseconds, user, request.Path, request.QueryString);
}
}

protected IActionResult AcResponse<T>(int status, string message, T data, List<string> errors = null)
{
var response = new APIResponse<T>(status, message, data, errors);
return StatusCode(status, response);
}
Application:
[HttpPost]
public async Task<IActionResult> Post([FromBody] AddEmailRequest model)
{
return await ExecuteActionAsync(async () =>
{

await Task.Delay(100);

var data = new { Id = 1, model.Email, Setting = _config.CurrentValue.Setting1 };

var ss = 0;
return (201, data, "Data posted successfully");

}, MethodBase.GetCurrentMethod().Name);
}

this or custom filter would be better for the cause?, in filter also i have to send the method name via reflecton anyways

just tying out things


aim: no try catch, + method name , user loged in , time taken all in every action

6 ответов

42 просмотра

Flat controller 🤮

Jass- Автор вопроса
D
Flat controller 🤮

everything in all controllers?

Стикер

Jass- Автор вопроса

thats for only exceptions, my main moto is get all the metrics

Jass
thats for only exceptions, my main moto is get all...

you can create a base class that has 1. status code 2. is success or not. 3. T Data for generic result 4. message for description of result

Jass- Автор вопроса
Mr Thieves
you can create a base class that has 1. status cod...

i do that for every response but i want metrics, will try reflection in middleware i have that ready too

Похожие вопросы

Обсуждают сегодня

30500 за редактор? )
Владимир
47
any reference of this implementation?
BitBuddha
29
Ⓐrtto, [4/23/24 7:02 PM] Please explain more fully how it is not working exactly, and what are the steps you are taking, and what error messages come or what happens. Ⓐrtto, ...
Ezza Kezza
2
sounds like people have lost their kaspa on tradeogre... does this mean tradeogre not trustworthy?
Ezza Kezza
15
Страшнейшая правда про списки ЦБ. С первых дней жизни P2P сферы, молодые человеки, начитавшись законодательной базы и "внутренних" документов, решили, что им противостоит сер...
Foxcool
3
Недавно Google Project Zero нашёл багу в SQLite с помощью LLM, о чём достаточно было шумно в определённых интернетах, которые сопровождались рассказами, что скоро всех "ибешни...
Alex Sherbakov
5
So much speculation in the last week. So much volatility in price. This is because Hedera has a GC that isn't using the network it's governing. Why aren't people asking why a...
Summit Seeker R
9
Anyone else having this error when trying to make transactions?
Datzel
11
Question: How viable is it to use Anvil as the backend infrastructure for managing a TradFi portfolio, while integrating Flexa for instant liquidity and payment solutions? Cou...
Kevin
2
вы делали что-то подобное и как? может есть либы готовые? увидел картинку нокода, где всё линиями соединено и стало интересно попробовать то же в ddl на lua сделать. решил с ч...
Victor
8
Карта сайта