Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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.

I can successfully throw my custom exception, the issue is it comes as a HTML view. I have seen ways to declare a custom error response, but I was hoping to be able to directly rethrow the exception as JSON.

Any ideas?

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

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

Thanks in advance for any help!

like image 535
Cyassin Avatar asked Aug 21 '14 10:08

Cyassin


2 Answers

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.

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.

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); 
        }
    }
like image 188
Cyassin Avatar answered Nov 18 '22 06:11

Cyassin


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.

$.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
        }
    });
like image 23
Matas Vaitkevicius Avatar answered Nov 18 '22 06:11

Matas Vaitkevicius