Похожие чаты

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 ответов

34 просмотра

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

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

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

Какой-то там пердун в 90-х решил, что есть какая-то разная типизация. Кого вообще это волнует?
КТ315
49
Hi. Do we have a raid bot? Why nobody doing raids on X? Even RH mentioned this and nobody paying attention...whats the channel for hex memes? If mods cant run raids just insta...
H
31
Подскажите, а есть vault lite или ченить такое?) А то нужен вольт для похода в вольт, но весит он ~500 мб) как-то многовато для парочки запросов ))
Alexandr Orloff
17
блеать, почему так?? где в роутере это исправляется?
Арсен Маньяков 🇦🇲
16
void terminal_scroll() { memmove(terminal_buffer, terminal_buffer + VGA_WIDTH, buffer_size - VGA_WIDTH); memset(terminal_buffer + buffer_size - VGA_WIDTH, 0, VGA_WIDTH); ...
Егор
47
🌊 Ocean Nodes Dashboard Update 🚀 Hey, Oceaners! First off, a massive round of applause 👏to all of you for the amazing engagement since we launched Ocean Nodes. In just a few ...
KreigDK | Never DM first🌊
3
Всем привет! Подскажите, пожалуйста, в чем ошибка? Настраиваю подключение к MySQL. Либы лежат рядом с exe. Все как по "учебнику"
Евгений
16
А можете как-то проверить меня по знаниям по ассемблеру?
A A
132
Здравствуйте! У меня появилась возможность купить книгу "Изучай Haskell во имя добра!". Но я где-то слышал, что эта книга устарела. Насколько это правда??
E
22
люди, которые используют flameshot, к вам вопрос. Можно-ли поставить хоткей на создание скриншота? В программе есть отдел "горячие клавиши", но там все для редактирования, скр...
ThunDer104
11
Карта сайта