Hiding the stacktrace for an exception returned by a asp.net WebMethod? - asp.net

I am using methods with the Attribute [WebMethod] in my aspx pages. I don't use any asp.net ajax but jQuery to call these methods and return objects in JSON. This all works fine.
Next I added an authorization check inside the webMethod, if the current user doesn't have access to the feature I need to let the calling JavaScript know.
So I am throwing an AccessViolationException exception which can then be parsed by the OnError callback function in JavaScript. This works too but the exception includes the full StackTrace and I don't want to make this available to the calling client.
What other ways I could use to return an "Access Denied" to the client when the WebMethod returns a business object?
I'm using ASP.Net 3.5SP1 and jQuery 1.32

You can also add a:
customErrors mode="On"/
in your web.config, this will cut away the stack trace and leave you only the exception message

Why propagate errors through the wire? why not use an error response ?
Just wrap your object in a response object wich can contain an error code for status and an error message to present to users.

As suggested by NunFur I changed my approach and rather than throwing an error, I return a 'richer' object.
There are at least two options, the first one would be to encapsulate my business object into a response object with some status properties. I tried this but it makes the JSON more complicated.
So rather than adding a new object I added two properties to my business object, something like ServiceStatus and ServiceMessage. By default these are 200 and '', but can be set by the WebMethod code if anything goes wrong (no access, proper error). In this case they business object will be 'empty' (no data). The JavaScript code then first checks for the ServiceStatus and reacts appropriately.
I add the two fields to all my objects that are returned by WebMethods, even a simple string. They have to implement an Interface with those two properties.
Now I have complete control over that goes over the wire in case something unexpected is happening.
Thanks for the input

I save exceptions for when things go really wrong. (e.g. can't connect to the database)
Either return nothing (null/nill/whatever), or return a false bool value.
Sorry that I don't have a better answer than that...I'll have to keep looking myself.

You could look at SoapException: http://msdn.microsoft.com/en-us/library/system.web.services.protocols.soapexception(VS.71).aspx
I'm just not sure, if it will work when it is called from JavaScript. Espeially if it's called with a get-request.
BTW AccessViolationException is to my best knowlegde ment to be thrown when the application is accessing memory it has no access to.
/Asger

Related

ASP.NET - displaying business layer errors in the presentation layer

Currently in the ASP.NET application I'm developing, basic validations (ie required fields) are being done in the Presentation Layer, using Validators and a ValidationSummary. This is working great for me specifically since the ValidationSummary will display multiple error messages (assuming multiple Validators are set to invalid).
I also have some validations being done in the business layer - due to their complexity (and data service layer reliance) I'd rather not keep them in the presentation layer. However, I'm not sure the best way to send these back to the presentation layer for display to the user. My initial consideration is to send back a List<string> with failed validation messages and then dynamically create a CustomValidator control (since apparently you can only bind one error message to one Validator control) for each error to show in the ValidationSummary when there are any.
I'm assuming I'm not the first one to come across this issue, so I'm wondering if anyone has any suggestions on this.
Thanks!
There are essentially two ways to do this: either by passing back an error code/object from your business layer, or throw out an exception. You can also combine both.
For an example, you can take a look SqlException class. When you send a SQL to SQL Server, it runs a query parser to parse your SQL first. If it sees syntax error, then it will throw out a SqlException and terminate the query. There may be multiple syntax errors in your query. So SqlExeption class has an Errors property that contains a list of errors. You can then enumerate through that list in your presentation layer to format your error message, probably with a CustomValidator.
You can also simply just return the error list without throwing an exception. For example, you can have your function to return a List in case at least one error occurred and return null in case the call was successful. Or you can pass List as an argument into your function. They are all fine, it all depends on which way you feel is more convenient. The advantage of throwing out an exception is it unwinds multiple call frames immediately, so you don’t have to check return value on every level. For example, if function A calls function B , B calls function C, C sees something wrong, then if let C to return an error object (or error code), then B has to have code to check whether C returned an error and pass that error code/value back, A have to check it as well ---- you need to check it on every level. On the other hand, if you just let C to throw an exception, then the code goes straight to the exception handler. You don’t have check return values on every level.

Which exception to throw when not finding a WebForms control which "should" be there

We have a WebForms Control which requires that the ID of another Control implementing ITextControl is provided.
What exception should we throw if there is no control with that ID or a control is found but it's not implementing the interface?
var text = Page.FindControl(TextProviderId) as ITextControl;
if (text == null) {
throw new WhatEverException(...);
...
Should we split it into two cases and throw one exception if there is no control with that ID, and another one if said control does not implement ITextControl? If so, which exceptions should we use then?
If the control should really be there, I would say that your web form is in an invalid state if it is missing, so I would probably go for InvalidOperationException:
The exception that is thrown when a method call is invalid for the object's current state.
This would be applicable to both scenarios; regardless of whether the control is missing or if it does not implement the expected interface, the containing object is in an invalid state.
If this is a scenario that is expected to happen for various reasons (let's say that you are making some tool that others will program against, and this is a situation that they might very well produce), perhaps you should instead create two custom exceptions that make it very clear what is happening and how to correct it (such as ControlNotFoundException and InterfaceNotFoundException or something similar).
ArgumentOutOfRangeException?
Whether or not you should split them up into different exceptions probably depends most on whether or not you think it is likely that anyone will ever want to distinguish the two exceptions in different catch blocks.
Not knowing exactly how this will be used, this seems like the kind of error that should be brought to the developer's attention, where rewriting code to point to the correct file or implement the correct interface is the proper action, rather than implementing a try-catch and give the user friendly error messages. As such, I'd just throw an ArgumentException.

How to abort an ASMX request based on logic in the constructor?

I have a common base class from which all my ASMX webservice classes will inherit. In the constructor, I want to do some common authentication checks; if they fail, I would like to halt processing right away (subclass's code would not get executed) and return a 401-status-code response to the caller.
However, the common ASPX-like ways of doing this don't seem to work:
Context.Response.End(); always kicks back a ThreadAborted exception to the caller, within a 500-status-code response. Even if I explicitly set Context.Response.StatusCode = 401 before calling End(), it is ignored. The result is still a 500-response, and the message is always "thread-aborted-exception".
MSDN suggests I use HttpContext.Current.ApplicationInstance.CompleteRequest() instead. However, this does not stop downstream processing: my subclass's functions are still executed as if the constructor had done nothing. (Kind of defeats the purpose of checking authorization in the constructor.)
I can throw a new HttpException. This is a little better in that it does prevent downstream processing, and at least it gives me control over the exception Message returned to the caller. However, it isn't perfect in that the response is still always a 500.
I can define a DoProcessing instance var, and set it to true/false within the constructor. Then have every single WebMethod in every single subclass wrap its functionality within an if (DoProcessing) block... but let's face it, that's hideous!
Is there a better / more thorough way to implement this sort of functionality, so it is common to all my ASMX classes?
edit: Accepting John's answer, as it is probably the best approach. However, due to client reluctance to adopt additional 3rd-party code, and some degree of FUD with AOP, we didn't take that approach. We ended up going with option #3 above, as it seemed to strike the best balance between speed-of-implementation and flexibility, and still fulfill the requirements.
The best way to do it would be to switch to WCF, which has explicit support for such a scenario.
If you must still use ASMX, then your best bet is to call the base class methods from each web method. You might want to use something like PostSharp to "magically" cause all of your web methods to call the base class method.
Context.Response.Write("My custom response message from constructor");
Context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
Context.Response.End();
That code prevent to pass in web method after constructor.

Custom Elmah YSOD data

I'm using Elmah with ASP.NET and wondering how I would add custom data, such as a session variable, to an unhandled exception email.
I've tried several handlers in the Global.asax file but can't seem to find the right one.
For this, I'd think you would need to modify the Elmah source and recompile. It shouldn't be too difficult to achieve. If you have a look in the constructor of the Elmah.Error class, the HttpContext is passed in, from which you should be able to get the info you need, e.g. Session, Form variables etc. You could add custom fields to the Elmah.Error class for this data
I think the Elmah.ErrorMailHtmlFormatter class is where the email is constructed using a HtmlTextWriter, and here you could insert code in the RenderSummary() method to include the custom fields you added to Elmah.Error.
I know it may be a pain to start working with source, but personally I think it's the cleanest way as there currently is no facility for report/email templates, and it's better that bolting on something to change the output after it has been generated.
Andrew's answer helped a lot, thanks. I ended up doing the following:
Added a OnBuilding event to the ErrorMail http module. The event args for this event have a NameValueCollection property.
I handled the OnBuilding event in global.asax.
Since HttpModules don't always have access to sessionstate, esp. if the exception occurs before the session is loaded, I copied the data i wanted reported into the HttpApplication cache(indexed by sessionid).
When an exception occurs I grab the data i want out of the application cache via the sessionid stored in the request(specifically, in the cookie). I generate a NameValueCollection from this data and send it back to the httpmodule via the OnBuilding args.
The data is then rendered to email similarly to how the server variables section is rendered.

ASP.NET control events exception handling

Suppose I have a button in an aspx page that performs a save of the form data to the database. In the associated event handler, before sending the updates, I read something from a webservice, operation that might result in an exception. In case of an error I want to have an adequate message displayed on the page, and all the data in the form preserved. How can I achieve this? Also, all my pages inherit from a basepage, so I would like, if possible to have all the error handling code in the base class. I do not want, if possible, to surround any web service call with try-catch blocks, I would in case of any unhandled exception to call some method automatically, something like Page_error, but still preserve the data in my forms.
You can easily put a method that manages the display message (maybe setting the text of some errorMessageLabel) in a superclass called from any derived class (if you wanna use inheritance to setup a template for your pages) if an exception is thrown (you can put the call to the superclas method in a catch block if there's actually an exception being thrown or you can manage this manually if the webservice is unavailable depending on your programming style).
As far as preserving the data presented, if viewstate is on and you are not populating your page dynamically then you're ok - if not, you need to explicitly save state information in viewState or session entries and retrieve them back if something goes wrong.
This bit really depends on how your page is actually implemented.

Resources