How to return an error in C # with Json Result?

1

I'm starting now with the C # language, and I came across the following task on a system, I must do an error handling and return this in Json Result, the returned data must be collected and sent by email ... that is, when generating the error on the page should appear the button "SEND ERROR REPORT" and this will be sent to my email. So it is giving error in the time to return, someone can tell me what is wrong in 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 looks like this:

<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 in the index I created this link to fire the view:

  @Html.ActionLink("Exemplo envolvendo erro não mapeado",
                 "ExemploErroNaoMapeado", "Home")
    
asked by anonymous 25.01.2018 / 12:45

1 answer

2

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

What I've done a couple of times, before working with the 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 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);

}

In javascript, you treat both success and error in success and leaves fail for communication failures or errors that were not actually treated by displaying a default message, such as: "Failed to process request" / p>

<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>
    
26.01.2018 / 00:40