500 Internal Error in ASP.NET MVC Ajax - c#

I'm using Visual Studio 2010 and MVC 4 for my web application. This is my controller code:
public ActionResult MyController()
{
if (Request.IsAjaxRequest())
{
using (MyContainer context = new MyContainer())
{
try
{
var result = Some Query;
return PartialView("_MyView", result);
}
catch (Exception ex)
{
}
}
}
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Home", new { area = "User" });
}
else
{
return Redirect("/");
}
}
This method will be done successfully, But my ajax container not showing any things. In firebug this error raised:
NetworkError: 500 Internal Server Error + http://localhost....?X-Requested-With=XMLHttpRequest
Why does this error occur?
What do I do to solve this problem?
Thanks in advance!

The 500 Internal Server Error message might be seen in any number of ways because something was not processed fine on the server. In your case, as the commends, your MyContainer type does not implement IDisposable interface, so, you cannot use this type on the using(){ } block. When you use a type on a using block, this type have to implement IDIsposable because when it get over, the .Net Framework will remove the instance from the heap and the reference. I did some changes on your code without using block. Take a look:
public ActionResult ActionName()
{
if (Request.IsAjaxRequest())
{
try
{
MyContainer context = new MyContainer();
var result = Some Query;
return PartialView("_MyView", result);
}
catch (Exception ex)
{
// return some partial error that shows some message error
return PartialView("_Error");
}
}
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Home", new { area = "User" });
}
return Redirect("/");
}

Related

Trying to show exception message in UI controller in ASP.NET MVC

In the configuration file I have made it so that the property Name of the class Series IsUnique() so whenever I try to add another entity with the same name, I get a DbUpdateException. I can access the message of this exception everywhere except for the UIController.
Here we have the code in my service where I check if the series is valid and if not I throw an exception (I know this is not best practice put at this point I just want it to work first)
public void Add(SeriesDTO series)
{
if (series.Name != null && series.Startdate < series.Enddate)
{
_unitOfWork.Series.AddAsync(_mapper.Map<SeriesDTO, Series>(series));
_unitOfWork.CommitAsync();
}
else
throw new Exception("Series data is not valid");
}
Then I have my controller where I check for the DbUpdateException and if I find it I throw another exception this I prefer not to do because at this point I can access this exception message with the right message.
[HttpPost("add")]
//POST: series/add
public IActionResult Add(SeriesDTO series)
{
try
{
_seriesService.Add(series);
}
catch (DbUpdateException E)
{
throw new Exception("Series with this name already exists.");
}
return Ok(series);
}
Up until this point I can always access the exception error but when I get to my UI controller then this exception turns into a 500 internal server error and thus I can not differentiate between an invalid entity exception and a DbUpdateException and thus cannot access the right message.
public IActionResult Add(SeriesDTO serie)
{
if(serie.Enddate < DateTime.Today || serie.Enddate.Equals(null))
{
serie.Active = false;
}
else
{
serie.Active = true;
}
try
{
string data = JsonConvert.SerializeObject(serie);
var result = _client.UploadString("series/add", data);
}
catch(Exception E)
{
ExceptionModel Exception = new ExceptionModel("Something went wrong with the series data.");
return View("Exception", Exception);
//return View("Create");
}
return Redirect("Index");
}
Does anyone know how to properly send the exception through to the UI controller?
You can do that.
In you Controller method :
public IActionResult Add(SeriesDTO serie)
{
//...
ModelState.AddModelError("CustomError", "You error message as string.");
//...
}
And in you view you need that :
<span asp-validation-for="CustomError" class="text-danger"></span>
If something doesn't work, tell me and edit you post with the code of you View.

Propagate exception message from service to controller .NET

I have a .NET appplication where there is a controller for receiving user requests, a service Service 1 which calls another service Service 2.
I have some code in the Service 2 where I query the database(DynamoDB) and get a 500 error in response when the user request values are incorrect. I want to handle this such that I catch this error/exception and send back the error message along with a 400 status code from the controller to the user. How should I modify the code to do this?
This is what I have tried. Currently, I'm just printing the error in Service 1 but I need to send it to the controller. Is sending the error message to the controller by throwing exceptions along the way the right way to do it?
The below code is similar to the actual code
Controller:
[HttpGet]
[Authorize(Policy = "Read-Entity")]
[Route("byParams/{param1}/{param2}")]
[Produces(typeof(DynamoResult<EntityResponse>))]
public async Task<IActionResult> ListByParams([FromQuery] DynamoQuery entityQuery)
{
try
{
return await HandleRequest(async () =>
{
return Ok((await _entityStore.ListByParams(entityQuery)));
});
}
catch (Exception e)
{
return BadRequest(e.Message);
}
}
Service 1:
public async Task<DynamoResult<EntityResponse>> ListByParams(DynamoQuery entityQuery)
{
results = new DynamoResult<Entity>();
try {
results = await GetPagedQueryResults(entityQuery);
}
catch (Exception e) {
Console.WriteLine(e);
}
return new DynamoResult<EntityResponse>
{
Data = results.Data.Select(_mapper.Map<EntityResponse>).ToList(),
};
}
Service 2:
private async Task<DynamoResult<TResponse>> GetPagedQueryResults(DynamoQuery query)
{
var results = new List<Document>();
try{
results = await search.GetNextSetAsync();
}
catch(Exception e){
throw new PaginationTokenException(e.Message);
}
return results;
}
[Serializable]
public class PaginationTokenException : Exception
{
public PaginationTokenException() { }
public PaginationTokenException(string message)
: base(message) {
throw new Exception(message);
}
public PaginationTokenException(string message, Exception inner)
: base(message, inner) { }
}
Assuming you want to hide implementation details from the controller (i.e. you don't want the controller to know/care that it's DynamoDB), I would create a custom exception and throw that from Service1.
Service1 would look something like this:
public async Task<DynamoResult<EntityResponse>> ListByParams(DynamoQuery entityQuery)
{
results = new DynamoResult<Entity>();
try {
results = await GetPagedQueryResults(entityQuery);
}
catch (Exception e) {
throw new MyCustomException('My error message', e);
}
return new DynamoResult<EntityResponse>
{
Data = results.Data.Select(_mapper.Map<EntityResponse>).ToList(),
};
}
In the controller you can then capture that exception explicitly:
[HttpGet]
[Authorize(Policy = "Read-Entity")]
[Route("byParams/{param1}/{param2}")]
[Produces(typeof(DynamoResult<EntityResponse>))]
public async Task<IActionResult> ListByParams([FromQuery] DynamoQuery entityQuery)
{
try
{
return await HandleRequest(async () =>
{
return Ok((await _entityStore.ListByParams(entityQuery)));
});
}
catch (MyCustomException e)
{
return BadRequest(e.Message);
}
}

Suppress error from Unit of Work transaction

I'm trying to suppress error in code, but MVC action still returns "500 internal server error".
What events are fired in ASP.NET Boilerplate framework after action returns?
public async Task<IActionResult> Post([FromBody]PaymentViewModel model)
{
var result = false;
// Storing of card must pass
try
{
// ...
}
catch (Exception ex)
{
// Catch business exception, but storing
}
return Json(new { result });
}
To recover in a catch block, begin a UnitOfWork with RequiresNew:
public async Task<IActionResult> Post([FromBody]PaymentViewModel model)
{
var result = false;
// Storing of card must pass
try
{
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
// ...
await CurrentUnitOfWork.SaveChangesAsync();
await uow.CompleteAsync();
}
}
catch (Exception ex)
{
// Catch business exception, but storing
}
return Json(new { result });
}
Further explanation: aspnetboilerplate/aspnetboilerplate#2732 (comment)

Displaying custom Error for static data class in Asp MVC

Hello Stackoverflow people,in my mvc project i have static class where i load static data then using it in controllers.
public class StaticData
{
public static List<ITEM_TYPES> _itemTypes ;
public static void LoadData()
{
try
{
using (pfservicereference.Service1Client ctx = new Service1Client())
{
_itemTypes = ctx.GetItemTypes();
}
}
catch (Exception ex)
{
throw new HttpException(500,ex.Message);
}
}
}
But how to redirect to Custom Error Page If i have HttpException Here?
I Have set customErrors mode="On" But it didnt helps.Is there any way to Redirect?
You can redirect to custom error page using following approaches,
Approach 1:
You can use try catch block inside action method and redirect to custom error page.
public ActionResult Index()
{
try
{
//Code logic here
}
catch (HttpException ex)
{
if (ex.ErrorCode == 500)
return RedirectToAction("error", "error");
}
return View();
}
Approach 2:
You can use exception filter for catching errors in application level, based on the error code we can redirect to custom error pages.
For this approach you can create separate exception filter class and mapped application level in global.asax or controller level.
protected override void OnException(ExceptionContext filterContext)
{
if (filterContext.Exception is HttpException)
{
HttpException exception = filterContext.Exception as HttpException;
if (exception.ErrorCode == 600)
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{ "action", "Error" },
{ "controller", "Error" }
});
filterContext.ExceptionHandled = true;
}
}

Is it possible to show Error Message in VOID type for webapi?

I am new to Web Api 2 , I want to show some message if i hit Exception , I know that VOID is a non return type, I tried with HttpResponseMessage but it is not working or showing the "Error Message" , is that any way to show message ?
My code is as below
public void Post(int id)
{
string result = string.Empty;
try
{
//some code
}
catch (Exception ex)
{
HttpResponseMessage response2 = Request.CreateResponse(HttpStatusCode.BadRequest, "Error message");
ErrId = 999;
}
}
If you are using web api 2, then I would use IHttpActionResult as the return type, which allows you to do something like:
public IHttpActionResult Post(int id)
{
string result = string.Empty;
try
{
//some code
return Ok();
}
catch (Exception ex)
{
return BadRequest("Error message");
}
}
However, it must be noted that by default Web API has a built-in exception handler and logger that will automatically return a 500 response code for any exception, so the code above is potentially redundant unless you are catching a custom exception. Lastly the code above does not log the exception.

Categories