2种方法有不同的参数和例外

时间:2017-04-16 19:56:09

标签: c# exception exception-handling try-catch

我有两种不同参数的方法:

await ocr.GetTextAsync(dataStream, filename, language);

await ocr.GetTextAsync(fileUrl, language);

这两种方法都可以返回相同的异常列表。所以,块像:

            try
            {
                 ocrResult = await ocr.GetTextAsync(dataStream, filename, language);
            }
            catch (FailedToProcessException failedEx)
            {
                _logger.AddLog("OCRController->GetTextAsync", $"Failed to process exception: '{failedEx.ErrorMessage}'", LogLevel.ERROR);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, failedEx.ErrorMessage);
            }
            catch(InternalServerErrorException intEx)
            {
                _logger.AddLog("OCRController->GetTextAsync", $"Internal server error exception: '{intEx.ErrorMessage}'", LogLevel.ERROR);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, intEx.ErrorMessage);
            }
            catch (Exception e)
            {
                _logger.AddLog("OCRController->GetTextAsync", $"Exception: '{e.Message}'", LogLevel.ERROR);
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "File can't be processed");
            }

是类似的。但我不想“复制/粘贴”部分代码。我怎么把它包装在一个地方?

2 个答案:

答案 0 :(得分:1)

您需要将要调用的方法作为参数传递 像

这样的东西
private static async Task Try(Func<Task<Object>> methodToRun)
{
        try
        {
            object ocrResult = await methodToRun();
        }

        catch (Exception e)
        {

        }
}

private static Task<object> Blabla(int v)
{
        throw new NotImplementedException();
}

private static Task<object> Blabla()
{
     throw new NotImplementedException();
}

你可以这样称呼它

await Try(() => Blabla());
await Try(() => Blabla(123));

答案 1 :(得分:0)

这是不可能具体的,缺乏一个好的Minimal, Complete, and Verifiable code example的问题,准确地显示了你正在做的事情。但是,类似下面的内容应该有效:

async Task<ResponseType> SafeAwaitResult(Task<ResultType> task)
{
    try
    {
        ocrResult = await task;

        // do something to return a "success" value for ResponseType
    }
    catch (FailedToProcessException failedEx)
    {
        _logger.AddLog("OCRController->GetTextAsync", $"Failed to process exception: '{failedEx.ErrorMessage}'", LogLevel.ERROR);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, failedEx.ErrorMessage);
    }
    catch(InternalServerErrorException intEx)
    {
        _logger.AddLog("OCRController->GetTextAsync", $"Internal server error exception: '{intEx.ErrorMessage}'", LogLevel.ERROR);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, intEx.ErrorMessage);
    }
    catch (Exception e)
    {
        _logger.AddLog("OCRController->GetTextAsync", $"Exception: '{e.Message}'", LogLevel.ERROR);
        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "File can't be processed");
    }
}

然后你可以使用这样的东西:

ResponseType response =
    await SafeAwaitResult(ocr.GetTextAsync(dataStream, filename, language));

如果您愿意,可以在重载中包装该语法:

Task<ResponseType> SafeAwaitResponse(Stream dataStream, string fileName, CultureInfo language)
{
    return SafeAwaitResult(ocr.GetTextAsync(dataStream, fileName, language))
}

我必须填写上面的一堆类型,因为你的问题并不具体。据推测,您可以基于这些示例推断出正确的实际语法。如果没有,请在您的问题中提供必要的详细信息。