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.
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>