0

I have an ASP.NET MVC web app that calls a Wep API. The Web API throws an exception but not sure how to catch it.

The Web API catches an error and throws it.

enter image description here

The ASP.NET MVC web app method that calls the Web API.

The "Try Catch" did not catch the error.

The line:

if (result.IsSuccessStatusCode) 

shows the status code is NOT successful so it falls into the false condition which just puts a friendly message into the viewbag.

Instead, I want to be able to something here in order to make the Error.cshtml to appear.

How do I throw the error message at this point to get the Error.cshtml to appear? The page has appeared under other error scenarios. I believe by having the 'HandleErrorAttribute' in the Filter.config.cs file.

    [HttpGet]
    public async Task<ActionResult> GetUserProfile()
    {
        if ((string)@Session["HasProfileSwitch"] == "False")
        {
            UserProfileForMaintViewModel userProfileForMaintViewModel = new UserProfileForMaintViewModel();
            return View("UserProfileMaint1", userProfileForMaintViewModel);
        }
        else
            try
            {
                string hostName = Dns.GetHostName();
                string myIpAddress = Dns.GetHostEntry(hostName).AddressList[2].ToString();
                UserProfileForMaintViewModel userProfileForMaintViewModel = new UserProfileForMaintViewModel();

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://localhost:56224");
                    string restOfUrl = "/api/profileandblog/getuserprofile/" + Session["UserName"] + "/" + myIpAddress + "/" + Session["UserId"];
                    client.DefaultRequestHeaders.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    // Call the web api - HTTP GET.
                    HttpResponseMessage result = await client.GetAsync(restOfUrl);

                    if (result.IsSuccessStatusCode)
                    {
                        var userResponse = result.Content.ReadAsStringAsync().Result;
                        userProfileForMaintViewModel = JsonConvert.DeserializeObject<UserProfileForMaintViewModel>(userResponse);
                    }
                    else
                    {
                        // The web api sent an error response.
                        ViewBag.errormessage = "Server error on getting the active userProflie. UserId: " + Session["UserId"] + " Please contact the administrator.";                          
                    }

                    return View("UserProfileMaint1", userProfileForMaintViewModel);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

This is what I have in the FilterConfig.cs - the ErrorLoggerAttribute points to a custom error logger.

using System.Web.Mvc;
using GbngWebClient.Helpers;

namespace GbngWebClient
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
            filters.Add(new ErrorLoggerAttribute());
        }
    }
}

This is the Error.cshtml:

@{
ViewBag.Title = "Error";
Layout = null;
}

<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="-1" />

 <style>
   .center {
    text-align: center;
    margin-left: auto;
    margin-right: auto;
    margin-bottom: auto;
    margin-top: auto;
  }
</style>

<link href="~/Content/bootstrap.min.css" rel="stylesheet" />

<div class="container">
    <div class="row">
        <div class="span12">
            <div class="hero-unit center">
                <h1>
                    Something Went Wrong!
                </h1>

                @if (TempData["ErrorMessage"] != null)
                {
                    <div class="alert alert-danger">
                        <strong>Oops!</strong> @TempData["ErrorMessage"]
                    </div>
                }
                else
                {
                    <div class="alert alert-danger">
                        An error occurred while processing your request.
                    </div>
                }

            <br />
            <p>Contact the Administrator.</p>
            <p><b>To go back home, just press this button:</b></p>
            <a href="/Home/Index" class="btn btn-large btn-info"><i class="icon-home icon-white">
            </i>Take Me Home</a>
            </div>
           <br />
           <p></p>
       </div>
    </div>
</div>
user3020047
  • 868
  • 1
  • 15
  • 45
  • 1
    Side note: Never rethrow an exception using `throw ex;`. Instead use `throw;` The latter preserves the stack trace so you can see where the exception originated from. `throw ex;` will reset the stack trace in the exception to the point where that is being called. – Igor Mar 19 '20 at 21:04
  • Igor..actually that was the way I originally had it but was trying things before I realized that the local 'try catch' was not catching the error as explained above. Thanks for the insight. – user3020047 Mar 19 '20 at 21:57
  • You should be `await`ing the call to `ReadAsStringAsync()` instead of accessing the `Result` property of the `Task` directly. Also, your `else` block is unnecessary, as is the nesting it adds, as you're returning early if the original `if` condition is matched. – John H Mar 19 '20 at 22:20
  • Not sure how to code that. I tried but ran into compile errors. My code works fine for most of my test cases. Except when there is an error to catch. So I think it is sound generally. I took these 2 examples as reference. https://www.c-sharpcorner.com/article/consuming-asp-net-web-api-rest-service-in-asp-net-mvc-using-http-client/ https://www.tutorialsteacher.com/webapi/consume-web-api-get-method-in-aspnet-mvc – user3020047 Mar 20 '20 at 00:21
  • Maybe your questions is answered [here](https://stackoverflow.com/questions/12519561/throw-httpresponseexception-or-return-request-createerrorresponse). – bdongus Mar 20 '20 at 02:22

0 Answers0