0

Hi I am trying to catch Exceptions inside this Action Controller, I want to show the exception in the Output and in a Modal, won't work in both scenarios

Method:

[HttpPost]
public ActionResult PostDepartment(Department DM)
{
    try
    {
        if (DM.OperationType == "Save")
        {
            using (dbConn ef = new dbConn())
            {
                Department dept = new Department();

                short Id = Convert.ToInt16(ef.Department.Max(field => (short?)field.DepartmentID) + 1 ?? 1);
                dept.DepartmentID = Id;
                dept.Name = DM.Name;
                dept.GroupName = DM.GroupName;
                dept.ModifiedDate = DateTime.Now;
                ef.Department.Add(dept);
                ef.SaveChanges();
            }
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
        return Json(new { error = ex.Message });
    }
    return new HttpStatusCodeResult(201);
 }

The breakpoint shows that the message is there

enter image description here

And then nothing happens, it goes to the success part of my ajax call

    error: function (e) {
        $.unblockUI();
        $('#errorModalmsg').text(e.responseJSON.error);
        $('#errorModal').modal('show');
    },
    success: function () {
        $.unblockUI();
        departmentPostSuccess();
        $('#departmentTable').DataTable().ajax.reload();
    }

What am I missing?

Edit: I am more concerned as to why Diagnostics.Debug isn't catching anything, I tried different type of errors

Edit 2 Solution: What I cared about was to bring the internal .NET Exception to the View so I found this way of doing so here in the end I couldn't make Diagnostics.Debug output work

catch (Exception ex)
{
    return new HttpStatusCodeResult(500, " :( Something bad happened: " + ex.Message);
}

Ajax, it also shows up in the browser console

error: function (xhr, httpStatusMessage, customMessage) {
   if (xhr.status === 500) {
        $.unblockUI();
        $('#errorModalMsg').text(customMessage);
        $('#errorModal').modal('show');
   }
}

enter image description here

  • `return Json(new { error = ex.Message });` will be a successful HTTP status code. Your ajax code will not detect it as an error condition. – Jasen Jul 18 '19 at 18:49
  • 1
    Possible duplicate of [Return JSON with error status code MVC](https://stackoverflow.com/questions/11370251/return-json-with-error-status-code-mvc) – JuanR Jul 18 '19 at 19:12

3 Answers3

1

return Json() basically means you actually respond with a 200 status code. That means your success code will actually execute instead.

If you want your error function to be called, then your request should fail (4xx or 5xx status codes).

A possible workaround:

success: function (response) {
        if(response.error){
           //do stuffs
           return;
        }
        $.unblockUI();
        departmentPostSuccess();
        $('#departmentTable').DataTable().ajax.reload();
    }
1

As others have pointed out, returning Json is essentially returning a 200 OK response. You need to return some kind of error.

Personally, I would avoid catching this generic exception unless you plan on adding logging of some kind or doing some kind of logic in the catch. However if you want to keep the catch, I would simply throw the exception after logging your exception message to the console:

catch (Exception ex)
{
    Debug.WriteLine(ex.Message);
    throw ex;
}
deruitda
  • 580
  • 4
  • 17
  • It says unhandled exception but I am throwing it at the output this is what bothers me I don't know why it doesn't show in the output console –  Jul 18 '19 at 20:14
  • @RobertoTorres are you referring to the output console in your web browser? Or your visual studio output console – deruitda Jul 18 '19 at 20:18
  • output in visual studio –  Jul 18 '19 at 20:21
  • See this question here and see if that solves your issue https://stackoverflow.com/questions/1159755/where-does-system-diagnostics-debug-write-output-appear – deruitda Jul 18 '19 at 20:22
  • The Console class is for console projects only, Debug is the one needed and it works with WebForms I suspect this isn't working due to the MVC nature of the project I am currently researching will post updates –  Jul 18 '19 at 20:30
  • Yes sorry I realized my mistake and deleted the comment shortly after posting it. – deruitda Jul 19 '19 at 12:03
0

you can pass the result of action by a variable in response like success, then in javascript check the success , if success is true show the success message else show the error message

success: function (response) {
        if (response.success) {
             $.unblockUI();
             departmentPostSuccess();
             $('#departmentTable').DataTable().ajax.reload();
        } else {
           $.unblockUI();
           $('#errorModalmsg').text(response.error);
           $('#errorModal').modal('show');
        }                          
    },
    error: function (response) {
        alert("error!");  // 
    }
 catch (Exception ex)
    {
        Debug.WriteLine(ex.Message);
        return Json(new { success=false, error = ex.Message });
    }
     return Json(new { success=true});
Farhad Zamani
  • 5,381
  • 2
  • 16
  • 41