How to return a C# error with Json Result?

Asked

Viewed 3,199 times

1

I am starting now with the language C#, and I came across the following task on a system, I must do an error treatment and return this in Json Result, the returned data should be collected and sent by email... ie, when generating the error on the page should appear the button "SEND ERROR REPORT" and this will be sent to my email. So you’re making a mistake when it comes time to return, someone can tell me what’s wrong with this code:

Homecontroller:

public ActionResult ErroNaoMapeado()
        {
            return View();
        }

        public JsonResult ExemploErroNaoMapeado()
        {
            try
            {
                throw new Exception(
                                "Exemplo envolvendo o lançamento de uma exceção não mapeada.");
            }
            catch (Exception ex)
            {
                return Json(new { msg = ex.Message, erro = true }, JsonRequestBehavior.AllowGet);
            }

        }

In the view Erronaomapeado this way:

<h2>
    Ocorreu um erro não mapeado durante a execução
    da última ação...
</h2>


<script type="text/javascript">
    $(document).ready(function () {
        //debugger;
        gerandoRelatorio();
        function gerandoRelatorio() {
            $.getJSON("Home/ExemploErroNaoMapeado", function (data) {
                console.log(data);

            }).fail(function (result) {
                if (data.erro == true) {
                    alert(data.msg);
                }
            });
        }
    });
</script>

And at the index I created this link to trigger the view:

  @Html.ActionLink("Exemplo envolvendo erro não mapeado",
                 "ExemploErroNaoMapeado", "Home")

1 answer

2


If you’re treating the Exception with the catch and returning the Json with the error message, will not fall into the fail()... For Jquery your Request was successful (Httpstatus 200).

What I’ve done a few times, before working with Web API, was to use a default class for responses and an Action where I redirected in case of error

Example:

public class ResponseViewModel{
    public object Data { get; set; }
    public bool Sucesso { get; set; }
    public string Mensagem { get; set; }
}

Redirecting to the error:

public ActionResult ExemploErroNaoMapeado()
{
    var response = new ResponseViewModel();
    try
    {            
        throw new Exception("Oops, ocorreu um erro");
    }
    catch(Exception e)
    {
        return ErroCapturado(e);
    }
    return Json(response, JsonRequestBehavior.AllowGet);
}

public ActionResult ErroCapturado(Exception ex)
{
    var response = new ResponseViewModel
    {
        Data = ex.Data,
        Sucesso = false,
        Mensagem = ex.Message
    };

   return Json(response, JsonRequestBehavior.AllowGet);

}

Already in javascript you treat both success and error in success and leaves the fail for communication failures or errors that were not actually handled presenting a standard message, such as: "Failed to process the request"

<script type="text/javascript">
    $(document).ready(function () {
        //debugger;
        gerandoRelatorio();
        function gerandoRelatorio() {
            $.getJSON("Home/ExemploErroNaoMapeado", function (response) {

                if(response.sucesso)
                {
                    console.log(response.data);
                }
                else
                {              
                    alert(data.mensagem);              
                }

            }).fail(function (response) { 
                //Erro genérico
                alert("Não foi possível processar a sua requisição");

            }); 
        }
    });
</script>
  • Could you show me what my code would look like??? Because I didn’t understand very well and I believe I won’t be able to adapt in the way you exemplified, because my knowledge is very limited yet!

  • the only problem is that the error when it is displayed is not displayed in a rendered way, but rather on a blank screen with error message, I wanted it to be displayed on the screen with the system layout!

  • I don’t understand, do you want when making an ajax request in case of any server error the user is redirected to another page to display the error? Wouldn’t it be better to use a notification? otherwise you have no reason to request it via javascript

  • i want the error to be displayed on a page, so I will create a button that by clicking this error report is sent to my email, understood??

Browser other questions tagged

You are not signed in. Login or sign up in order to post.