Alireza
Alireza

Reputation: 168

try catch does not work for "return Json()" exceptions

When the length of characters in json result is large the following exception will be raised:

Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.

The above exception is a server side exception with 500 response code so if we put the source code inside a try catch block, the error should be caught in catch block, but try catch does not work for this scenario.

You could test this problem by following code, please use it inside an asp.net mvc controller:

public JsonResult Test()
    {
        try
        {
            var result = "";
            var v1 = new JavaScriptSerializer();

            for (int i = 0; i < (v1.MaxJsonLength / 100) + 10; i++)
            {
                result += "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
            }

            //exception message:
            //Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
            return Json(result, JsonRequestBehavior.AllowGet);
        }
        catch
        {
            //when exception is raised the catch will not be called

            return null;
        }


    }

Upvotes: 1

Views: 2419

Answers (2)

Andrei Filimon
Andrei Filimon

Reputation: 1188

Try like this:

ActionResult result;
try
        {
            var result = "";
            var v1 = new JavaScriptSerializer();

            for (int i = 0; i < (v1.MaxJsonLength / 100) + 10; i++)
            {
                result += "0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789";
            }

            //exception message:
            //Error during serialization or deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.
            result= Json(result, JsonRequestBehavior.AllowGet);
        }
        catch
        {
            //when exception is raised the catch will not be called
        }
return result;

Upvotes: -2

Zoran Horvat
Zoran Horvat

Reputation: 11301

I cannot reproduce the error, but anyway what is happening to you is that the Json method implementation is already catching the exception internally and converting it to full-blown HTTP 5xx response. There is no exception coming out from the return Json() call.

There is no chance for you to catch the exception because... what would you do? Generate an HTTP 5xx response? That is already done for you by the MVC framework.

Upvotes: 4

Related Questions