Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Catching exception in async Task which returns value

I’m working on a .NET Core app which uses Google Sheets Api. I’m using async tasks to avoid freezing guis. My trouble starts here. These async tasks connect Google Sheets and return some values. One of tasks:

public async Task<String> KullaniciBilgileriniAl()
    {
        String range = "Kullanici Bilgileri";
        SpreadsheetsResource.ValuesResource.GetRequest request = this.service.Spreadsheets.Values.Get(spreadsheetId, range);
        ValueRange response = await Task.Run(() => request.Execute());
        IList<IList<Object>> values = response.Values;
        String DataKullaniciAdi = (String) values[1][0];
        String DataSifre = (String)values[1][1];
        return DataKullaniciAdi + DataSifre;
    }

What i’m trying to do is catch exceptions if there’s no internet connection. If there’s no connection, errors accure on this line:

ValueRange response = await Task.Run(() => request.Execute());

I’ve tried add this line into try-catch statement like that:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

try
{
    ValueRange response = await Task.Run(() => request.Execute());
    IList<IList<Object>> values = response.Values;
    String DataKullaniciAdi = (String)values[1][0];
    String DataSifre = (String)values[1][1];
    return DataKullaniciAdi + DataSifre;
}

catch (Exception ex)
{
    System.Diagnostics.Debug.WriteLine(ex);
}

but tasks run on different threads. So it didn’t work.

In summary, i need to catch any exception which accures in Task.Run() function. How can i do that?

>Solution :

Well first of all remove Task.Run as it serves no purpose. You are create a task to run a synchronous method which is not needed. However, if you really want to keep it there for whatever reason, catch the exception within the task:

ValueRange response = await Task.Run(() => {

    try {
        return request.Execute();
    } catch Exception(Exception e){
        return null;
    }
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading