使用自定义类处理 Azure 函数中的错误

问题描述 投票:0回答:1

我的登录功能如下所示:

[Function("Loginxyz")]
public async Task<IActionResult> GenerateToken(
        [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "user/login")] HttpRequestData req,
        ILogger log)
{
    try
    {
        if (requestData.BarCode != null)
        {
            var localLoginRequest = JsonConvert.DeserializeObject<xyz>(requestBody);
            token = await _tokenService.GenerateToken(localLoginRequest);
        }

        if (token == null)
            return new UnauthorizedResult();

        return new OkObjectResult(new { access_token = token });
    }
    catch (AggregateException ae)
    {
        // Handle multiple exceptions
        foreach (var innerException in ae.InnerExceptions)
        {
            log.LogError(innerException, "An error occurred");
            // Handle the inner exception based on its type
        }

        // Return a specific error response based on the aggregate exception
        return new BadRequestObjectResult("An error occurred");
    }
    catch (AuthenticationServiceException ex)
    {
        // Log the error with detailed message
        log.LogError($"Error during token generation: {ex.Message}", ex);

        // Create a custom error response object
        var errorResponse = new
            {
                Error = ex.Message,
                StatusCode = StatusCodes.Status400BadRequest
            };

        // Return the error response with the appropriate status code
        return new JsonResult(errorResponse) { StatusCode = StatusCodes.Status400BadRequest };
    }
    catch (LoginConflictException ex)
    {
        // Log the error with detailed message
        log.LogError($"Error during token generation: {ex.Message}", ex);

        // Create a custom error response object
        var errorResponse = new
            {
                Error = ex.Message,
                StatusCode = StatusCodes.Status409Conflict
            };

        // Return the error response with the appropriate status code
        return new JsonResult(errorResponse) { StatusCode = StatusCodes.Status409Conflict };
    }
    catch (Exception ex)
    {
        log.LogError($"Error during token generation: {ex.Message}");
        return new StatusCodeResult(StatusCodes.Status500InternalServerError);
    }
}

我的服务类如下所示:

public async Task<TokenResponseDto> GenerateToken(object tokenRequest)
{
    try
    {
        return await tokenGenerator.GenerateToken(tokenRequest);
    }
    catch (Exception ex)
    {
        throw; // Rethrow the exception
    }
}

异常跟踪:-

 Function 'Login', Invocation id '': An exception was thrown by the invocation. [2024-07-13T02:28:21.903Z] Result: Function 'Login', Invocation id '': An exception was thrown by the invocation. Exception: System.ArgumentNullException: Value cannot be null. (Parameter 'logger') [2024-07-13T02:28:21.903Z]    at System.ThrowHelper.Throw(String paramName) [2024-07-13T02:28:21.904Z]    at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args) [2024-07-13T02:28:21.904Z]    at Microsoft.Extensions.Logging.LoggerExtensions.LogError(ILogger logger, String message, Object[] args) [2024-07-13T02:28:21.905Z]    at ..AzureFunctions.Funtions.User.LoginFunction.GenerateToken(HttpRequestData req, ILogger log) in \Funtions\User\LoginFunction.cs:line 86 [2024-07-13T02:28:21.907Z]    at ..DirectFunctionExecutor.ExecuteAsync(FunctionContext context) in ..\Microsoft.Azure.Functions.Worker.Sdk.Generators\Microsoft.Azure.Functions.Worker.Sdk.Generators.FunctionExecutorGenerator\GeneratedFunctionExecutor.g.cs:line 38 [2024-07-13T02:28:21.909Z]    at Microsoft.Azure.Functions.Worker.OutputBindings.OutputBindingsMiddleware.Invoke(FunctionContext context, FunctionExecutionDelegate next) in D:\a\_work\1\s\src\DotNetWorker.Core\OutputBindings\OutputBindingsMiddleware.cs:line 13 [2024-07-13T02:28:21.909Z]    at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.FunctionsHttpProxyingMiddleware.Invoke(FunctionContext context, FunctionExecutionDelegate next) in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\FunctionsMiddleware\FunctionsHttpProxyingMiddleware.cs:line 48 [2024-07-13T02:28:21.910Z]    at Microsoft.Azure.Functions.Worker.FunctionsApplication.InvokeFunctionAsync(FunctionContext context) in D:\a\_work\1\s\src\DotNetWorker.Core\FunctionsApplication.cs:line 89 Stack:    at System.ThrowHelper.Throw(String paramName) [2024-07-13T02:28:21.911Z]    at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger, LogLevel logLevel, EventId eventId, Exception exception, String message, Object[] args) [2024-07-13T02:28:21.912Z]    at Microsoft.Extensions.Logging.LoggerExtensions.LogError(ILogger logger, String message, Object[] args) [2024-07-13T02:28:21.915Z]    at ..Funtions.User.LoginFunction.GenerateToken(HttpRequestData req, ILogger log) in .\Funtions\User\LoginFunction.cs:line 86 [2024-07-13T02:28:21.916Z]    at ..DirectFunctionExecutor.ExecuteAsync(FunctionContext context) in ..\Microsoft.Azure.Functions.Worker.Sdk.Generators\Microsoft.Azure.Functions.Worker.Sdk.Generators.FunctionExecutorGenerator\GeneratedFunctionExecutor.g.cs:line 38 [2024-07-13T02:28:21.917Z]    at Microsoft.Azure.Functions.Worker.OutputBindings.OutputBindingsMiddleware.Invoke(FunctionContext context, FunctionExecutionDelegate next) in D:\a\_work\1\s\src\DotNetWorker.Core\OutputBindings\OutputBindingsMiddleware.cs:line 13 [2024-07-13T02:28:21.918Z]    at Microsoft.Azure.Functions.Worker.Extensions.Http.AspNetCore.FunctionsHttpProxyingMiddleware.Invoke(FunctionContext context, FunctionExecutionDelegate next) in D:\a\_work\1\s\extensions\Worker.Extensions.Http.AspNetCore\src\FunctionsMiddleware\FunctionsHttpProxyingMiddleware.cs:line 48 [2024-07-13T02:28:21.919Z]    at Microsoft.Azure.Functions.Worker.FunctionsApplication.InvokeFunctionAsync(FunctionContext context) in D:\a\_work\1\s\src\DotNetWorker.Core\FunctionsApplication.cs:line 89. [2024-07-13T02:28:58.728Z] Executed 'Functions.Login' (Failed, Id=b4005c4b-a335-46f7-8dc7-cf24b1d62fe7, Duration=48071ms) [2024-07-13T02:28:58.730Z] System.Private.CoreLib: Exception while executing function: Functions.Login. Microsoft.Azure.WebJobs.Script.Grpc: Failed to proxy request with ForwarderError: RequestCanceled. System.Net.Http: The operation was canceled. System.Net.Sockets: Unable to read data from the transport connection: The I/O operation has been aborted because of either a thread exit or an application request.. The I/O operation has been aborted because of either a thread exit or an application request.

我在

tokenGenerator.GenerateToken
方法中抛出一个错误,并在我的服务类中重新抛出它。我的期望是,当我在服务类中重新引发错误时,它应该在我的 Azure 函数中被捕获,但这种情况没有发生。

但是,我从重新抛出中得到的错误是:

调用抛出异常。
异常:System.ArgumentNullException:值不能为空。 (参数“记录器”)

我已在我的 cmd 日志中捕获了这一点。

这很令人困惑,因为我抛出了一个自定义错误,与

ArgumentNullException
无关。

有人可以帮助我理解这一点吗?

c# asp.net error-handling azure-functions azure-cosmosdb
1个回答
0
投票

使用自定义类处理 Azure 函数中的错误

我确实同意@Peter Bons 的观点,并且要使用自定义类进行错误处理,请按照以下步骤操作:

Program.cs 添加

rith.AddSingleton<RithwikInterface, Test_Rithwik_Class>()
和 Logging 如下:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using FunctionAppRith;

var ri_test = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices(rith =>
    {
        rith.AddLogging();
        rith.AddSingleton<RithwikInterface, Test_Rithwik_Class>(); 
    })
    .ConfigureLogging((context, logging) =>
    {
        logging.AddConsole(); 
    })
    .Build();

ri_test.Run();

Function.cs 添加:

using Microsoft.Azure.Functions.Worker;
using System.Net;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.Extensions.Logging;


namespace FunctionAppRith
{
    public class Function1
    {
        private readonly ILogger<Function1> ri_lger;
        private readonly RithwikInterface rith_ser;

        public Function1(ILogger<Function1> lg, RithwikInterface riser)
        {
            ri_lger = lg ?? throw new ArgumentNullException(nameof(lg));
            rith_ser = riser ?? throw new ArgumentNullException(nameof(riser));
        }

        [Function("Function1")]
        public async Task<HttpResponseData> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req)
        {
            try
            {
                ri_lger.LogInformation("Hello Rithwik");
                var tout = await rith_ser.Tst_Rith_fun();
                var res_out = req.CreateResponse(HttpStatusCode.OK);
                await res_out.WriteStringAsync(tout);
                return res_out;
            }
            catch (CustomException rith)
            {
                ri_lger.LogError(rith, "Hello Rithwik, This is a Custom Error.");
                var res_out = req.CreateResponse(HttpStatusCode.BadRequest);
                await res_out.WriteStringAsync("Hello Rithwik, This is a Custom Error.");
                return res_out;
            }
            catch (Exception rith)
            {
                ri_lger.LogError(rith, "Hello Rithwik, This is a unexpected Error.");
                var res_out = req.CreateResponse(HttpStatusCode.InternalServerError);
                await res_out.WriteStringAsync("Hello Rithwik, This is a unexpected Error.");
                return res_out;
            }
        }
    }
    public interface RithwikInterface
    {
        Task<string> Tst_Rith_fun();
    }
    public class Test_Rithwik_Class : RithwikInterface
    {
        public async Task<string> Tst_Rith_fun()
        {
            throw new CustomException("Hello Rithwik Bojja, Created an Exception/Error");
        }
    }
    
    public class CustomException : Exception
    {
        public CustomException(string message) : base(message) { }

    }
}

输出:

enter image description here

enter image description here

在 try {} 块中,您使用登录代码然后对其进行测试。

© www.soinside.com 2019 - 2024. All rights reserved.