8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

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

garish 3月前

88 0

我的登录功能如下所示:[Function(\'Loginxyz\')]public async Task生成令牌([HttpTrigger(AuthorizationLevel.Anonymous,\'post\',路线=&

我的登录功能如下所示:

[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:值不能为空。(参数“logger”)

我已经在我的 cmd 日志中捕获了此信息。

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

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

帖子版权声明 1、本帖标题:使用自定义类在 Azure 函数中处理错误
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由garish在本站《asp.net》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 我有一个这样的结构:typedef struct { int row; int col; double *entries;} Matrix;我想编写函数来创建、释放等。例如:Matrix *mtalloc(typeof((Matrix) {}.row)...

    我有一个像这样的结构:

    typedef struct {
        int row;
        int col;
        double *entries;
    } Matrix;
    

    我想要编写函数来创建、释放等等。例如:

    Matrix *mtalloc(typeof((Matrix) {}.row) row, typeof((Matrix) {}.col) col)
    {
        Matrix *p = malloc(sizeof(Matrix));
    
        if (p == NULL) {
            fprintf(stderr, "mtalloc(%x, %x): malloc returned NULL\n", row, col);
            exit(EXIT_FAILURE);
        }
    
        p->row = row;
        p->col = col;
        p->entries = malloc(sizeof(*((Matrix) {}.entries)) * row * col);
        return p;
    }
    

    这样,如果结构体中字段的类型发生变化,函数就不需要改变,但这是好的还是坏的做法?

返回
作者最近主题: