How to handle an ASP.NET MVC ActionResult Exception? - asp.net-mvc

I have a custom ActionResult which is more deeply encountering System.Web.HttpException when the remote host closes the connection. I've already overridden the Controller's OnException method but it's not getting caught there. The ASP.NET MVC pipeline is already done executing my Controller's Action and is now executing the returned ActionResult when it encounters this exception.
Presently, it's bubbling up and being cluttering my log as an ERROR. I'd rather not filter these out at logging time, because I don't consider a remote host aborting the download of the content to be an error.
I'd rather handle this error directly, but I can't tell where. Controller.OnException doesn't work, and so I doubt the IExceptionFilter would either. I could use Application_OnError but I fear that is too high up.
Isn't there a more MVC'ish way?

There are no other points to catch exceptions between Controller.OnException and Application_OnError. Be Brave and use Application_OnError

You can use HandleErrorAttribute to handle exceptions thrown in the controller action. As you pointed out in your question, I would suspect the error is beyond the scope of this attribute. That would leave only Application_OnError.
You could add a whitelist to your error handling code to ignore specific errors (specific type with specific code and maybe specific source/stacktrace).

Related

Handle SignalR constructor exceptions

Is there anyway to handle exceptions which are thrown in Hub constructor methods?
Currently there is only HubPipelineModule which can handles only calling methods related exceptions but not constructor exception.
Assume in Hub constructor I get the "Database connection error". Now I want to show the end user a proper message.
I checked the following links but they are not helpful in this case :
SignalR exception logging?
SignalR, Owin and exception handling
Your best bet for handling exceptions thrown from a Hub constructor is probably by providing your own IHubActivator.
Here is an example of how you can replace SignalR's IHubActivator. In that example the purpose for replacing IHubActivator was to use Simple Injector to activate hubs, but the same principle applies if you just want to handle/log any exceptions thrown during Hub construction.

Building a WebAPI for an N-tier web application - appropriate practices for error handling?

I have a web application with the following layers:
Client(s)
WebAPI
Services
Repository
Core
I'm not sure where to put error handling though. Within the webAPI controllers, should I just have try/catch statements? Is it ok to throw errors in the services/repository code? I'm trying to avoid passing any data to the client, other than some friendly error message.
Business errors should be handled in your service layer (for example things like username already exists). Putting try/catch statements in all your controller actions could quickly become cumbersome and lead to repetitive code. You may take a look at the custom error handling article which provides examples of handling various errors in the Web API such as custom error filters (deriving from the ExceptionFilterAttribute class and overriding the OnException method).
You can create a custom exception type that would be intercepted by an ExceptionFilter or http module. It would set the HTTP status code and description. Optionally, it can also return a serialized object with the error data.
Other exception types would return status code 500.

Form Validation and HTTP Exception

A form is submitted using jQuery form plug-in to an action in MVC framework. In the action, if form validation fails a reply should be sent back to the client. jQuery form plug-in comes with error and success callbacks (like any other jQuery Ajax functions).
Isnt it a better practice to return an HTTP Exception with error-code 400 (Bad Request) and catch it in error callback rather than returning a successful HTTP response and catching it in success callback?
If the answer is yes, wouldn't it be more descriptive to have data attached to HTTP Exception?
From what I see right now, HTTPException.Data is readonly. One of the constructors seems to do the job (HttpException(SerializationInfo, StreamingContext)) but I cant wrap my head around it.
Would someone please explain for me how to add data to HTTP Exception?
No, it's not better practice to simply return an error code, even if you do manage to attach messages to the HTTPException.
Why? Well, you lose so much information that way. You have the option to return an arbitrary JSON object, which could include (for example) a list of all validation errors (or indeed, any pertinent info which may help the calling client out), which you then render on the client so that the user is able to correct.
Also, you've got to consider what happens when your call is successful. Is a 200 return code really enough for your purposes?

Mvc async operation crashes iis

Scenario: Site uses Mvc async controller.
Error: Everytime an async end operation (like EndReceive) throws an error it also crashes IIS.
This is the type of error one should always try to catch but is the default behavior otherwise always crashing the IIS process? (don't know if i should leave it or start more in depth troubleshooting)
Thanx,
I think you will find the following blog post useful in understanding what happens under the covers.

Correct way to handle ASP.NET MVC system errors

Which is the best way to handle a system error in ASP.NET MVC? I've watched a video on DimeCast.net in which the guy used the global.ascx file to write a method Application_Error to handle the errors. But currently, I'm handling my errors inside the web.config file.
Could someone point me in the right direction on how to properly handle errors? This could be:
syntax error
exceptions
404 and other page/file not found errors
The application is fairly large.
Take a look at elmah for logging of unhandled exceptions, there's actually a quick example on nuget demo video
I use combination of elmah for unhandled exceptions, and nLog to log ones that I can handle but still want to log. Thus far the combination has worked out very well.
Very likely you are going to need a combination of approaches. Some errors can be handled directly in your models, others in your controllers, and some others might need to be handled all the way to the application level (either via web.config or via the global.ascx.)
I prefer to handle the errors in the global.ascx rather than via redirection in web.config because in the global.ascx I have more information about the request that caused the error where as if I do a redirect via the web.config settings some of that information is lost by the time my error page receives the request.
A few weeks ago I just noticed that 404 errors are better not handled via the web.config because that (by design) causes an HTTP redirect code 302 rather than a true HTTP 404 code that indicates the client that the resource does not exist. I have a post on my blog where I cover this in detail http://hectorcorrea.com/Blog/Returning-HTTP-404-in-ASP.NET-MVC
Using ELMAH as Brook suggested is also a very good idea.

Resources