简体   繁体   English

MVC Rethrow自定义异常为JSON

[英]MVC Rethrow custom exception as JSON

I am calling a web service from my MVC view and wanting to use the jquery ajax error functionality on exception throw. 我从我的MVC视图调用Web服务,并希望在异常抛出时使用jquery ajax错误功能。

I am trying to throw a custom created exception from my MVC business layer into my presentation layer controller and rethrow it as a json response. 我试图将自定义创建的异常从我的MVC业务层抛出到我的表示层控制器中,并将其重新抛出为json响应。

I can successfully throw my custom exception, the issue is it comes as a HTML view. 我可以成功抛出自定义异常,问题在于它是HTML视图。 I have seen ways to declare a custom error response, but I was hoping to be able to directly rethrow the exception as JSON. 我已经看到了声明自定义错误响应的方法,但我希望能够直接将该异常重新抛出为JSON。

Any ideas? 有任何想法吗?

Javascript: 使用Javascript:

$.ajax({
            type: "POST",
            url: 'create',
            data: "{userDetails:" + JSON.stringify(details) + "}",
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                data = data.d;
                redirectSuccess();
            },
            error: function(err) {
                //display thrown exception here
            }
        });

CS CS

public JsonResult create(MyModel.New details)
        {
            try
            {
                Library.insert(details);
                return Json(true); 
            }
            catch (Exception ex)
            {
                throw;
            }
        }

Thanks in advance for any help! 在此先感谢您的帮助!

I ended up working out a solution appropriate. 我最终找到了合适的解决方案。

For anyone wanting a similar answer to the question I asked, what i did was declare a custom filter. 对于想要对我问的问题做出类似回答的人,我所做的就是声明一个自定义过滤器。 The main parts of this is setting the filter result to return as JSON, but even then it would return as success in the jquery ajax call because it returned a status of 200 which jquery ajax reads as success. 这个主要部分是将过滤结果设置为以JSON形式返回,但即使这样,它也会在jquery ajax调用中返回成功,因为它返回状态200,jquery ajax读取为成功。

Jquery ajax reads any status outside of 200 as an error so as you can see I changed the status code to a custom number that i created and will document and therefore the jquery ajax sees an error and throws it to ajax error. Jquery ajax读取200之外的任何状态作为错误,因此您可以看到我将状态代码更改为我创建并将记录的自定义数字,因此jquery ajax会看到错误并将其抛出到ajax错误。

public class MyErrorHandlerAttribute : FilterAttribute, IExceptionFilter
    {
        public void OnException(ExceptionContext filterContext)
        {
            filterContext.HttpContext.Response.StatusCode = 11001;
            filterContext.ExceptionHandled = true;
            filterContext.Result = new JsonResult

            {
                Data = new { success = false, error = filterContext.Exception.ToString() },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }
    }

To reference the current filter, you just add the error handler attribute to the function as shown in the first line below: 要引用当前过滤器,只需将错误处理程序属性添加到函数中,如下面第一行所示:

[MyErrorHandler]
public JsonResult create(MyModel.New details)
    {
        try
        {
            Library.insert(details);
            return Json(true); 
        }
        catch (Exception ex)
        {
            return Json(ex.Message); 
        }
    }

I don't think it works the way you think it does you need to pass exception to frontend as responce. 我不认为它的工作方式你认为你需要将异常作为响应传递给前端。

public JsonResult create(MyModel.New details)
    {
        try
        {
            Library.insert(details);
            return Json(true); 
        }
        catch (Exception ex)
        {
            return Json(ex.Message); 
        }
    }

And then handle it with JS as success. 然后用JS成功处理它。

$.ajax({
        type: "POST",
        url: 'create',
        data: "{userDetails:" + JSON.stringify(details) + "}",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            if (data.Message)
            {
             //display error
             }else{
            data = data.d;
            redirectSuccess();}
        },
        error: function(err) {
            //display thrown exception here
        }
    });

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

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