1

I'm new to ASP.NET and MVC. In my controller I'm throwing ArgumentException on invalid user input. I like the fact that the client is getting some info back in JSON format. But I don't want to send the whole stacktrace, just the exception message (which contains a useful, localized explanation of the error).

How should I go about doing this?

I've seen some Application_Error() and FilterException, but they all seem to be redirecting to a special "error" view, whilst I want to stay on the same page and just print out a dialog with the user-friendly explanation.

Howie
  • 2,760
  • 6
  • 32
  • 60

2 Answers2

1

Look at this answer ASP.NET MVC Ajax Error handling and also if you need StatusCode:

filterContext.HttpContext.Response.StatusCode = 500;
Community
  • 1
  • 1
webdeveloper
  • 17,174
  • 3
  • 48
  • 47
  • The `OnException` method isn't being called. Is there something I need to configure? Note: I didn't change the controller code. – Howie Oct 04 '12 at 08:10
  • @Howie You need attribute `[MyErrorHandler]` or global registering, but then you must check request for content type and return json only for `application/json` – webdeveloper Oct 04 '12 at 08:16
1
HttpContext.Response.StatusCode = 400
return new ContentResult{Content="My custom error"};

In this case ajax will treat response as in error state and you can specify your custom message and get to it from response.responseText property

$.ajax({
 .....
error: function(e){
  alert(e.responseText); // your  error message
}
});
odesuk
  • 1,197
  • 1
  • 12
  • 10