chobo2
chobo2

Reputation: 85765

How does the execption handling work with jquery and asp.net mvc?

I been playing around with my code and I wanted to see what would happen if I did this.

I load up my asp.net mvc page and then go to my mssql 2005 database and hit pause. I then click on a link that has a jquery ajax request.

It goes to a method in my controller(lets say it is a JsonResult type) it has a ActionVerb of "Post" and Authentication attribute set.

Now in my code I have a SqlExpection catch statement what should catch all SqlExceptions and then return a json result with a generic message that says "database down".

This way the user knows what is going on but no potential error message is given that could give a hacker info to see why the database went down.

So I expected my error message to be shown. but instead I look in the response and I get this huge long message saying "Database is paused and this and this failed".

So basically everything I don't want the user to know about. Luckly it does not show up in my message container since it does not look to be a JsonResult but anyone with firebug will see it.

So it is not even making it into my method. So there must be some other place that this error is occurring.

So Why is my exception not catching this? Is it because of my attribute tags? Since it looks like it never goes into the method at all.

Thanks

Here is the stack trace portion of what comes back.

 <b>Stack Trace:</b> <br><br>

            <table width=100% bgcolor="#ffffcc">
               <tr>
                  <td>
                      <code><pre>

[SqlException (0x80131904): SQL Server service has been paused. No new connections will be allowed. To resume the service, use SQL Computer Manager or the Services application in Control Panel.
Login failed for user 'myPc'.
A severe error occurred on the current command.  The results, if any, should be discarded.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1951450
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4849003
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2394
   System.Data.SqlClient.SqlDataReader.ConsumeMetaData() +33
   System.Data.SqlClient.SqlDataReader.get_MetaData() +83
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +297
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +954
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method) +32
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method) +141
   System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior) +70
   System.Web.Security.SqlRoleProvider.GetRolesForUser(String username) +760
   System.Web.Security.RolePrincipal.IsInRole(String role) +164
   System.Linq.Enumerable.Any(IEnumerable`1 source, Func`2 predicate) +159
   System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +218
   System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +35
   System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +99
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +399
   System.Web.Mvc.Controller.ExecuteCore() +126
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +151
   System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +57
   System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) +75
</pre></code>

Upvotes: 0

Views: 452

Answers (2)

David Andres
David Andres

Reputation: 31781

I believe your try/catch block is in the action method, but that the failure occurs before the action executes. Specifically, I think the failure is in the AuthorizeCore method where you make the GetRolesForUser call.

This code may be provided by MVC, and it wouldn't suprise me if adequate safety measures weren't put in place for data access. Worst case scenario: you may need to create a custom Authorize attribute and override its AuthorizeCore method or override the OnAuthorization method of the Controller you're extending.

To create your own Authorize attribute:

public class MyAuthorizeAttribute: AuthorizeAttribute
{
  protected override bool AuthorizeCore(HttContextBase httpContext)
  {
    var isAuthorized = //your code here;
    return isAuthorized;
  }
}

You can now use this attribute in place of Authorize, as in:

[MyAuthorize(Roles = "Admin")]
public ViewResult MyAction()
{
  ...
}

To override the Controller's OnAuthorization method:

protected void OnAuthorization(AuthorizationContext filterContext)
{
  var isAuthorized = //your code here;

  if(!isAuthorized) 
  {
    filterContext.Result = new HttpUnauthorizedResult();
  }
}

EDIT: This gets around the issue of a messy exception being sent back to the client. What it doesn't help with is your ability to catch this exception and return something meaningful back (e.g., the database is down). The problem is that we can capture the fact that the database is down in the Authorize method, which is where we should indicate that the user is not authorized. However, because the user is not authorized the action method will not fire, and so your ability to throw something back to the client is limited.

For lack of a better way of handling this, you may want to allow the user in via the OnAuthorizationMethod, but as you're doing this you can set a class property to a known value. When you enter the action method, you can inspect this value and act at that point. It's a hack, and your mileage will vary...

Alternatively, you can add a [HandleError(View="...")] attribute to your action method. I don't know if this while fire as a result of an error in the Authorize step and this will not return a JSONResult and you intended.

Upvotes: 1

olle
olle

Reputation: 4595

It sounds like you are seeing an exception which comes with a stracktrace (set debug to true in web.config) it should tell you the type of exception (perhaps you are catching the wrong type like David Andres suggests) and it will also contain the line numbers from the stack indicating where it's being thrown.

p.s. there is no question or even question mark in your "question" so I assume this is what you are looking for.

Upvotes: 1

Related Questions