简体   繁体   English

如何在JavaScript中捕获.NET异常?

[英]How to catch a .NET exception in javascript?

I'm building a webapp using ASP C#.NET MVC3. 我正在使用ASP C#.NET MVC3构建一个webapp。

I have a View ( .cshtml file ). 我有一个视图( .cshtml文件 )。 In this View I have a javascript function "SomeFunction()" which calls a .NET function through Razor like so: "@Html.Raw(Json.Encode(Model))". 在此视图中,我有一个JavaScript函数“ SomeFunction()”,该函数通过Razor调用.NET函数,例如:“ @ Html.Raw(Json.Encode(Model))”。 So everything put together it looks like: 因此,所有内容汇总如下:

SomeFunction(){
    var sections = @Html.Raw(Json.Encode(Model));
}

Note the @ please. 请注意@。

This function throws an exception (this exception to be exact: Increase json response maxJsonLength in MVC 4 ) when the size of the string exceeds the maximum (too many sections basically). 当字符串的大小超过最大值时(基本上是太多部分),此函数将引发异常(确切地说是此异常: 增加MVC 4中的json响应maxJsonLength )。 Well the requirements of my website don't instruct me to actually deal with this (luckily) by retrieving the data in pieces async and whatnot. 好吧,我网站的要求并没有指示我实际(幸运地)通过异步地提取数据来解决这个问题。 I'm fortunate enough to simply catch this exception and tell the user: "Too many sections! Please define a larger size for sections." 我很幸运,可以简单地捕获此异常并告诉用户:“节太多!请为节定义更大的尺寸。” Or something like this. 或类似的东西。 Alas I don't really understand how to do this exactly. las,我真的不太了解该怎么做。 I've tried the following: 我尝试了以下方法:

SomeFunction(){
    try {
        var sections = @{try {
            Html.Raw(Json.Encode(Model));
        } catch (Exception e) {
            throw new Exception("Exception caught in .NET");
        }}
    } catch(err) {
        alert('.NET exception caught in Javascript!');
    }
}

Note the @ infront of the 'try' to denote Razor syntax. 注意“ try”的@ infront表示Razor语法。

The 'alert' in the catch clause in javascript is never reached. 永远不会到达javascript中catch子句中的“警报”。 I come from desktop dev so I'm still a web novice. 我来自台式机开发人员,所以我仍然是Web新手。 How is this normally done? 通常如何做?

Thanks a lot in advance for helping me. 在此先非常感谢您的帮助。

Technically, you can't. 从技术上讲,您不能。

Because these are two separate languages running in separate environments (one on the server, the other on the client) the best thing to do is to catch the exception within the ASP.NET application and then return the exception to the client side formatted as a string along with some indication as to whether the execution was successful or not. 因为这是在不同的环境中运行的两种不同的语言(一种在服务器上,另一种在客户端上),所以最好的办法是在ASP.NET应用程序中捕获异常,然后将异常返回为格式为字符串以及有关执行是否成功的一些指示。

As simple example would be this ajax request/response: 一个简单的例子就是这个ajax请求/响应:

Our custom response object: 我们的自定义响应对象:

public class JsonResponse
{
    public bool Success { get; set; }
    public string Message { get; set; }
}

Usage: 用法:

[HttpPost]
public JsonResult DeleteMember(int id)
{
    try {
        this.memberService.DeleteMember(id);
    }
    catch (Exception ex)
    {
        return Json(new JsonResponse { Success = false, Message = ex.ToString());
    }
    return Json(new JsonResponse { Success = true });
}

Then your client side Javascript would have the object returned to it, where you'll be able to see if the request was successful, and if not then what the exception/error message was. 然后,客户端Javascript将把对象返回给它,在那里您将能够查看请求是否成功,如果不是,那么异常/错误消息是什么。

<script type="text/javascript">

$(function() {
    $.post('@Html.Action("Member", "DeleteMember")', function(response) {
        if (response.Success == false) {
            alert(response.Message);
        } else {
            alert("Member was deleted!");
        }
    });
});

</script>

you are mixing two things here. 您在这里混合两件事。 The Javascript is executed on client side and the c# code resides and throws exceptions on the server side. Javascript在客户端执行,而c#代码驻留在服务器端并引发异常。

so what basically is happening here is that when this view is being rendered. 所以这里基本上发生的是渲染此视图时。 this code is executed 该代码被执行

@try{
            Html.Raw(Json.Encode(Model));
        } catch (Exception e) {
            throw new Exception("Exception caught in .NET");
        }
    } catch(err) {
        alert('.NET exception caught in Javascript!');
    }

and finally what is send to client is the output of Html.Raw(Json.Encode(Model)) which in turn generated nothing. 最后发送给客户端的是Html.Raw(Json.Encode(Model))的输出,该输出Html.Raw(Json.Encode(Model))什么也没有产生。 as you have not included the @ prefix. 因为您尚未包含@前缀。

Instead what you can do is check the length of the string on the client side itself 相反,您可以做的是在客户端本身上检查字符串的长度

SomeFunction(){
    var sections = "@Html.Raw(Json.Encode(Model))";
    if(sections.length > [MAX LENGTH]){alert(SOMETHING);}
    else{
       sections = JSON.parse(sections);
       //your old code here
     }
}

If you're creating your javascript function via Razor(which sounds some kind of strange!) you should decide how to manage the exception, server side or client side. 如果要通过Razor创建Javascript函数(听起来有些奇怪!),则应决定如何管理异常(服务器端或客户端)。 The code below is an exception management which will occur at the server side which I think suits for you: 下面的代码是一个异常管理,它将在服务器端发生,我认为适合您:

SomeFunction(){
    string sections; 
    @try {
        sections = Html.Raw(Json.Encode(Model));
    } 
    catch (Exception e) {
        sections = "Error";
    }

    if (sections == "Error")
    {
        alert("Your message");
    }
}

you may try this 你可以试试这个

SomeFunction(){
    var sections = @{try {
        Html.Raw(Json.Encode(Model));
    } catch (Exception e) {
        Html.Raw(false)
    }}
    if(!!sections){
        alert('.NET exception caught in Javascript!');
    }
}

Big Joe, Parv Sharma and mehrandvd all have a point. Big Joe,Parv Sharma和mehrandvd都有观点。 I realize that now. 我现在意识到了。 Thanks again for contributing. 再次感谢您的贡献。 And I'm sorry I didn't immediatly understood your answers. 很抱歉,我没有立即理解您的答案。

However none was exactly usefull in my situation. 但是,在我的情况下,没有一个是完全有用的。 Atleast... I tried Big Joe's and couldn't get it to work like i wanted to (because a Post leads to reloading the page which I didn't need). Atleast ...我尝试了Big Joe's,却无法按我想要的那样工作(因为Post导致重新加载不需要的页面)。

What I did was: 我所做的是:

In the Action of the Controller where my Model (a collection of Sections) is filled I already try now to serialize the collection to Json (so that is server side). 在控制器的动作中,我的模型(部分的集合)被填充了,我现在已经尝试将集合序列化为Json(因此是服务器端)。 This looks like: 看起来像:

            List<Models.Section> sections = Models.Section.GetSectionsByCampaignID(campaignID);

            try {
                string sectionsAsJson = System.Web.Helpers.Json.Encode(sections);
            } catch (Exception) {
                sections = null;
            }

Now all I had to do in the javascript in the View is checking for null, like so: 现在,我在View中的javascript中要做的就是检查null,如下所示:

    var sections = @Html.Raw(Json.Encode(Model));

    if(sections != null){
        //Some code to do stuff with the sections.
   }  else {
        alert('Sorry for the inconvenience, but there are too much sections to draw. This is causing a technical error. Please edit the map and define a bigger section size.');
    }

So yeah, maybe not how experienced web developers would solve it. 是的,也许经验丰富的Web开发人员无法解决该问题。 But it works for me. 但这对我有用。 Does any experienced web developer foresee any major issues with this? 是否有经验丰富的Web开发人员预见到与此相关的任何重大问题? Please comment. 请评论。 I'm always ready to learn more. 我随时准备学习更多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM