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
Flat controller 🤮
everything in all controllers?
Стикер
thats for only exceptions, my main moto is get all the metrics
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
i do that for every response but i want metrics, will try reflection in middleware i have that ready too
Обсуждают сегодня