return error message with actionResult
Asked Answered
N

6

42

MVC App, client makes request to server, error happens, want to send the msg back to the client. Tried HttpStatusCodeResult but just returns a 404 with no message, I need the details of the error sent back to the client.

public ActionResult GetPLUAndDeptInfo(string authCode)
{
    try
    {
        //code everything works fine
    }
    catch (Exception ex)
    {
         Console.WriteLine(ex.Message);
         return new HttpStatusCodeResult(404, "Error in cloud - GetPLUInfo" + ex.Message);
    }
}
Nicky answered 10/2, 2014 at 16:26 Comment(0)
C
37

You need to return a view which has a friendly error message to the user

catch (Exception ex)
{
   // to do :log error
   return View("Error");
}

You should not be showing the internal details of your exception(like exception stacktrace etc) to the user. You should be logging the relevant information to your error log so that you can go through it and fix the issue.

If your request is an ajax request, You may return a JSON response with a proper status flag which client can evaluate and do further actions

[HttpPost]
public ActionResult Create(CustomerVM model)
{
  try
  {
   //save customer
    return Json(new { status="success",message="customer created"});
  }
  catch(Exception ex)
  {
    //to do: log error
   return Json(new { status="error",message="error creating customer"});
  }
} 

If you want to show the error in the form user submitted, You may use ModelState.AddModelError method along with the Html helper methods like Html.ValidationSummary etc to show the error to the user in the form he submitted.

Carcass answered 10/2, 2014 at 16:28 Comment(0)
C
27

One approach would be to just use the ModelState:

ModelState.AddModelError("", "Error in cloud - GetPLUInfo" + ex.Message);

and then on the view do something like this:

@Html.ValidationSummary()

where you want the errors to display. If there are no errors, it won't display, but if there are you'll get a section that lists all the errors.

Chandless answered 10/2, 2014 at 16:30 Comment(1)
I'm a bit torn on this! It seems OP's use case is when an exception happens when some service isn't available. This issue then isn't with the model, right? Rather something in the processing, so I feel like this answer misappropriates the ModelState. - If OP wants to show a warning instead of an error, there is nothing to switch on. Any thoughts?Ajar
P
17

Inside Controller Action you can access HttpContext.Response. There you can set the response status as in the following listing.

[HttpPost]
public ActionResult PostViaAjax()
{
    var body = Request.BinaryRead(Request.TotalBytes);

    var result = Content(JsonError(new Dictionary<string, string>()
    {
        {"err", "Some error!"}
    }), "application/json; charset=utf-8");
    HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
    return result;
}
Prove answered 6/6, 2016 at 7:54 Comment(4)
where did you get the JsonError from?Mikelmikell
@EhsanZargarErshadi: I think I found it: learn.microsoft.com/en-us/uwp/api/windows.data.json.jsonerrorMotorcycle
Thanks for this line HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;Corbin
Just to add to the answer. You can put error message to StatusDescription. Also, if you handle Exceptions then you need to override OnException method of the MVC controller.Noakes
A
5

IN your view insert

@Html.ValidationMessage("Error")

then in the controller after you use new in your model

var model = new yourmodel();
try{
[...]
}catch(Exception ex){
ModelState.AddModelError("Error", ex.Message);
return View(model);
}
Antebellum answered 10/2, 2014 at 16:32 Comment(0)
K
0

Not sure if this applies for everyone but I had a similar issue where I was returning a result to an AJAX call in my view and I wanted the custom error message to appear, and this article solved it perfectly for me (ASP.NET MVC 5 ajax error statusText is always "error"). TLDR. Response.TrySkipIisCustomErrors = true; Response.StatusCode = (int)HttpStatusCode.BadRequest; Response.ContentType = "text/plain"; return Content("Error" + Environment.NewLine + ex.Message);

Karynkaryo answered 13/3, 2023 at 17:28 Comment(0)
M
0

When the client can be configured to handle exceptions.

IActionResult GetData(string id)
{
    try
    {
        // code
    } 
    catch (Exception ex)
    {
        throw new Exception("<CustomMessage>", ex);
    }
}

When the client just needs a response string.

IActionResult GetData(string id)
{
    try
    {
        // code
    } 
    catch (Exception ex)
    {
        return "<ERCODE>:"+ex.Message;
    }
}
Melancholic answered 26/4 at 15:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.