Search code examples
c#asynchronousasync-awaitwebrequest

Try Catch Async WebRequest Put


I'm having some problems getting this to code to try and catch... I've tried try catch in several places such as before the encoding, inside the await before the write, before the flush but having no luck what so ever...

var encoder = new ASCIIEncoding();
var data = encoder.GetBytes(limitBody);
req.ContentLength = data.Length;

    await req.GetRequestStreamAsync().ContinueWith(trs =>
    {
        trs.Result.Write(data, 0, data.Length);
        trs.Result.Flush();

        Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)delegate
        {
            Methods.ReadStreamFromResponse(req.GetResponse(), requestUri, siteCode, correlationtoken, "PUT",
                    txtLimitsResponse, null, limitBody, _userId);
        });
   });

Whenever The remote server returns an error: (400) Bad Request.

The application breaks, How can I catch this error and output it to the user?

Many thanks


Solution

  • You should be able to just put the try/catch around the await. It already registers the rest of the method as a continuation so you don't need the ContinueWith and if you call this from the UI thread you don't need the Dispatcher.Invoke as await stores the current SynchornizationContext and restores it after the await. So the rest of the method will run on the UI thread as well.

    var encoder = new ASCIIEncoding();
    var data = encoder.GetBytes(limitBody);
    req.ContentLength = data.Length;
    
    try
    {  
        var result = await req.GetRequestStreamAsync(); 
        result.Write(data, 0, data.Length);
        result.Flush();
    
        Methods.ReadStreamFromResponse(req.GetResponse(), requestUri, siteCode, correlationtoken, "PUT",
                        txtLimitsResponse, null, limitBody, _userId);      
    }
    catch(...)
    { 
       ....
    }