Могу ли я вернуть настраиваемую ошибку из JsonResult в метод ошибки jQuery ajax?

Как передать настраиваемую информацию об ошибке из метода ASP.NET MVC3 JsonResult в ошибку (или успех или полный , если нужно) функция jQuery.ajax () ? В идеале я хотел бы иметь возможность:

  • По-прежнему выдавать ошибку на сервере (это используется для ведения журнала)
  • Получать настраиваемую информацию об ошибке на клиенте

Вот базовая версия моего кода :

Метод JsonResult контроллера

public JsonResult DoStuff(string argString)
{
    string errorInfo = "";

    try
    {
        DoOtherStuff(argString);
    }
    catch(Exception e)
    {
        errorInfo = "Failed to call DoOtherStuff()";
        //Edit HTTP Response here to include 'errorInfo' ?
        throw e;
    }

    return Json(true);
}

JavaScript

$.ajax({
    type: "POST",
    url: "../MyController/DoStuff",
    data: {argString: "arg string"},
    dataType: "json",
    traditional: true,
    success: function(data, statusCode, xhr){
        if (data === true)
            //Success handling
        else
            //Error handling here? But error still needs to be thrown on server...
    },
    error: function(xhr, errorType, exception) {
        //Here 'exception' is 'Internal Server Error'
        //Haven't had luck editing the Response on the server to pass something here
    }
});

Вещи, которые я пробовал (но не сработало):

  • Возвращение информации об ошибке из блока catch
    • Это работает, но исключение не может быть сгенерировано
  • Редактирование HTTP-ответа в блоке catch
    • Затем проверил xhr в обработчике ошибок jQuery
    • xhr.getResponseHeader () и т. Д. Содержал страницу ошибок ASP.NET по умолчанию, но я не думаю, что моя информация
    • это возможно, но я просто ошибся?
29
задан Drew Gaynor 15 February 2012 в 17:45
поделиться

1 ответ

Если по некоторым причинам Вы не можете отправить ошибку сервера. Вот опция, которую можно сделать.

сторона сервера

 var items = Newtonsoft.Json.JsonConvert.DeserializeObject<SubCat>(data); // Returning a parse object or complete object

        if (!String.IsNullOrEmpty(items.OldName))
        {
            DataTable update = Access.update_SubCategories_ByBrand_andCategory_andLikeSubCategories_BY_PRODUCTNAME(items.OldName, items.Name, items.Description);

            if(update.Rows.Count > 0)
            {
                List<errors> errors_ = new List<errors>();
                errors_.Add(new errors(update.Rows[0]["ErrorMessage"].ToString(), "Duplicate Field", true));

                return Newtonsoft.Json.JsonConvert.SerializeObject(errors_[0]); // returning a stringify object which equals a string | noncomplete object
            }

        }

        return items;

сторона клиента

 $.ajax({
            method: 'POST',
            url: `legacy.aspx/${place}`,
            contentType: 'application/json',
            data:  JSON.stringify({data_}),              
            headers: {
                'Accept': 'application/json, text/plain, *',
                'Content-type': 'application/json',
                'dataType': 'json'
            },
            success: function (data) {

                if (typeof data.d === 'object') { //If data returns an object then its a success

                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 3000
                    })

                    Toast.fire({
                        type: 'success',
                        title: 'Information Saved Successfully'
                    })

                    editChange(place, data.d, data_);

                } else { // If data returns a stringify object or string then it failed and run error

                    var myData = JSON.parse(data.d);

                    Swal.fire({
                      type: 'error',
                      title: 'Oops...',
                      text: 'Something went wrong!',
                      footer: `<a href='javascript:showError("${myData.errorMessage}", "${myData.type}", ${data_})'>Why do I have this issue?</a>`
                    })
                }
            },
            error: function (error) { console.log("FAIL....================="); }
        });
0
ответ дан 28 November 2019 в 01:15
поделиться
Другие вопросы по тегам:

Похожие вопросы: