Handling a scenario of an unavailable database in an MVC application - asp.net

In this scenario I wish too bypass my normal error logging, which wont work, and simply request the Error view and and send an email. I don't wish to duplicate this special case handling in all controllers, and DB access might be attempted before any action is requested. Where should I place this special handler, and if not in a controller, how do I call up the Error view?
Oh yes, I'm using Elmah for routine logging of unhandled exceptions.

Try using something along these lines in your controller
[HandleError(ExceptionType = typeof(SqlException), View = "SqlError")]
Public Class ProductController: Controller {
public ViewResult Item(string itemID)
{
Item item = ItemRepository.GetItem(itemID);
return View(item);
}
}
Now in your Views/Shared/ folder you can create a View called "SqlError.aspx" that will be returned if there's a SQL Exception.
I would also recommend handling all of your Application Error "stuff" in the Global.asax file. IE: the part that does the emailing of the error, logging of the error, etc.
Check out this SO question for an idea
ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I don't know what you code is but assuming the logging is done in some global error handling thing then edit the error handling to be like this should do it:
try
{
//logging
}
catch(SqlException)
{
//send email
return View("Error");
}

Related

Advice on exception handling in webservice

I need some advice on a good exception handling strategy in my webservice.
My web service methods are doing the standard CRUD operations against an Oracle database. Therefore, I have some methods that select data and return a dataset and others that do either an insert/update/ or delete and don't return anything.
Initially, I had all my code in each webservice method in a try-catch-finally catching an Oracle exception. I read some articles on the web that says this is not good and I should only surround something in try-catch if there is a potential for an exception. Now I am thinking that maybe it would be best if I put only my Insert/Update/Delete methods in try-catch-finally blocks.
So my questions are:
Should I put all my methods in try-catch-finally? They all interact with Oracle and could potentially cause an exception. Or should I only do this for the Insert/Update and Delete methods?
I don't really have any requirements on what they want to happen when an exception does occur. I am just going on common sense. I know that they definitely don't want the app to end. I am planning on logging the exception in some manner and re-throwing it to the client. I am doing this when there is an Oracle Exception.
Basically you need to do try-catch on every WebMethod. Since the event won't bubble up, I think there is no other better way.
However, you can use the trick in this post to make your life easier.
The way he does is creating a utility method like this and invoke that method by passing it a delegate to your web method logic.
private T Execute<T>(Func<T> body)
{
//wrap everything in common try/catch
try
{
return body();
}
catch (SoapException)
{
//rethrow any pre-generated SOAP faults
throw;
}
catch (ValidationException ex)
{
//validation error caused by client
ClientError innerError = new ClientError();
//TODO: populate client error as needed
//throw SOAP fault
throw this.GenerateSoapException(
"An error occurred while validating the client request.",
SoapException.ClientFaultCode,
innerError);
}
catch (Exception ex)
{
//everything else is treated as an error caused by server
ServerError innerError = new ServerError();
//TODO: populate server error as needed
//TODO: log error
//throw SOAP fault
throw this.GenerateSoapException(
"An unexpected error occurred on the server.",
SoapException.ServerFaultCode,
innerError);
}
}
I assume you are using ASP.NET WebMethods. My advice is that you always catch exceptions on the service layer, write a log and throw a SoapException. Basically you can try-catch on each service method (WebMethod). If you fail to do so, you would be exposing exception details to the client calling the service and that could be a potential security issue.

Propagating AccessDeniedException in Spring Security

In my web application I am using Spring Security and Spring MVC.
I have secured a couple of methods with #Secured annotation and configured Spring Security in such a way that when one of those methods is accessed without the proper role, the user is taken to the login page. However, I do not want that behaviour when the offending request comes from Ajax, so I implemented the custom #ExceptionHandler annotated method to determine the request's context.
This is my exception handler:
#ExceptionHandler(AccessDeniedException.class)
public void handleAccessDeniedException(AccessDeniedException ex, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (isAjax(request)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
} else {
throw ex;
}
}
This way I can both handle the exception myself (for example, log an attempt of accessing the #Secured method) and then let Spring do its part and redirect the user to the login page by rethrowing the AccessDeniedException. Also, when the request comes from Ajax I set the response status to SC_UNAUTHORIZED and handle the error on the client side.
Now, this seems to be working fine, but I am getting the following ERROR each time I rethrow the exception from the handleAccessDeniedException method:
ERROR org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Failed to invoke #ExceptionHandler method: public void app.controller.BaseController.handleAccessDeniedException(org.springframework.security.access.AccessDeniedException,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) throws java.lang.Exception
org.springframework.security.access.AccessDeniedException:
at app.controller.BaseController.handleAccessDeniedException(BaseController.java:23)
at app.controller.BaseController$$FastClassByCGLIB$$8f052058.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
(...)
I have not added any exception handling specifics to spring xml configuration files.
I do not see any issues with the app itself, but the error is there and since I am quite new to Spring MVC and Spring Security, I am guessing that I am not doing this properly. Any suggestions? Thanks!
Your exception handler isn't supposed to throw another exception. It's supposed to deal with it and send a response. It's a good idea to check the code if you get an error from a class to see how it behaves.
For the non-ajax case, you'd be better to redirect the response to the login page, if that's what you want. Alternatively, you can customize the AuthenticationEntryPoint used by Spring Security instead and omit AccessDeniedExceptions from MVC handling. The behaviour would essentially be the same as the defaul LoginUrlAuthenticationEntryPoint but you would extend it to return a 403 when an ajax request is detected.

Is it possible to write a base class to handle nullReferenceException from all pages?

I am using .net framework 4.0, plain asp.net and working with webform. Currently I having a base class to handle all parameter passing and redirect. I wonder is it possible to write a base class to handle nullRefeerenceException from all pages in once, lets say redirect end user to somewhere or display particular error message.
Scenario: For example, some pages must come along with parameter, if no parameter captured, I would like to redirect them to somewhere.
You can try to control the ProcessRequest. You need to test it to see if can do the work you ask for, but this is a good point to capture all errors of your page.
public override void ProcessRequest(HttpContext context)
{
try
{
base.ProcessRequest(context);
}
catch (Exception x)
{
// handle here your error from the page...
}
}
Some more notes
I was use this code on one critical page, but I do not use it for all my page. Even tho can capture the errors, some times you can not do nothing else here other than throw again the final error, so end up that is better to log your unknown and unhandled errors from globa.asax Application_Error, and on page make sure that you use try/catch to handle them where they happens.
After some think maybe is not good practice to use it. Good practice is to use try/catch in the place that you may have throws and not a general one like that.
Last
You also get throw error here when the user close the connection before the end of the render, but if you log the errors you get the same on Application_Error - this is not a page error.
Exception of type 'System.Web.HttpUnhandledException' was thrown. --->
System.Web.HttpException: The remote host closed the connection.
The error code is 0x80072746.
In you Global.asax, handle Application_Error.
When a NullReferenceException is handled by the server a 500 response is created. Redirect all of your server 500 messages however you want. This guide will help.
Definitive Guide to Handling 500 Errors in IIS6, IIS7, ASP.NET MVC3 with Custom Page
You can hook up to every uncatched NullReference Exception, depending on what you want to do.
For instance you can use the global.asax, to be specific the Application_Error Event. You can get a reference to the exception, look for the type and perform a redirect there.
Another way to get ahold of exceptions would be to write your custom error provider, but that wouldn't give you the possibility to perform a redirect.

Is it best to handle SQL Exceptions or rather use a customError page and the Application_Error method in Global.asax?

I am using ASP.Net 2.0. I found myself in an awkward situtation because I could not find the cause of an error. Up until now I have been using this idiom when it comes to accessing data.
try
{
access data
}
catch (SqlException exception)
{
Response.redirect("error.aspx");
}
finally
{
Dispose of connections, commands etc
}
Now I can never see what the actual error was because it is always handled. Sometimes I can run SQL Profiler and catch the last statement and run that in SQL Query Analyzer and see if there is a problem. That is obviously terrible.
So I thought that the global.asax Application_Error method would save me and I would email myself the exception. But this method seems to only be called for unhandled exceptions. So my question is, is rather better to not handle the exception at all, the system sends the email and use a customError page. Or is it better to ram the exception into the session, redirect to the error.aspx and try and do something with the error then. Is there a way to call Application_Error again? Because if I throw the exception again at the error.aspx then I get the yellow screen of death?
In my opinion, use a library (log4net for example) to log your exceptions and throw the exception again, let the asp.net redirect the error page to a custom page with web.config customErrors section.
Log4Net or Enterprise Library's Exception Handling Application Block both have email sending features.
Also take a look at ELMAH, very smart and pluggable exception handling module.
Logging would be invaluable here. In your catch blocks, log the error out to a log file. its a good idea to get in the habit of doing this at it can be a real life saver to see whats going on. Have a look at nlog which is a logging library. There are various tools out there too that allow you to analyse logs produced by nlog
Since you are using ASP.NET 2.0, your best bet is to do nothing.
ASP.NET added a feature called ASP.NET Health Monitoring. By default, this will log detailed exception information to the Application event log. It can be configured to send different kinds of problem to different destinations.
So, simply do nothing, and everything will be fine.
You can simply log the exception somewhere before redirecting to the Error page.
Something like :
try
{
//access data
}
catch (SqlException exception)
{
LogException(exception);
Response.redirect("error.aspx");
}
finally
{
//Dispose of connections, commands etc
}
Thus you can have it both ways, Customer will be directed to error page and still your exception is logged somewhere for you to review and get to the bottom of it.
By the way, there are many free logging libraries that you can use notably log4net and Enterprise library

Wrapping a web service in try/catch block

Is it best practice to wrap a web service method/call into a try/catch block?
I don't web service requests tend to be the reason why the .NET desktop applications crash? So I was thinking all calls should be wrapped in try/catch to prevent this.
Good idea?
Also, should it throw an exception or just have an empty catch?
I am assuming you are using WCF, since your question is tagged with it. A good practice in exception handling with WFC is not allowing exceptions to bubble across the wire to your consumer, but throw meaningful FaultExceptions instead.
You should always have a try...catch block in your operation if there is any chance an exception could be generated by it. If you allow the raw excption to bubble, only two scenarios can result: If you have configured your service to allow exception details in faults, you will expose internals of your service opening up yourself for security breaches. Or you don't have this configured in your service and the consumer gets a very generic message that indicates something went wrong, which is not very useful for them or the support team.
What you should do is declare one or more FaultExceptions, depending on what messages you want the user to receive from your operation, decorate them as FaultContracts on your operation declaration. Then you can try...catch specific exceptions and throw specific Faults. You can also have a try...catch that catches exception and throw a very general Fault.
The key here, is not revealing too much information of what is going on with your operation internally - especially stack traces!
The fault is just another data contract, so it is declared in your WSDL. This means that your consumer can catch the fault specifically and can react to faults thrown from your operation as if it was an exception being thrown from their code.
Hope this helps.
Joe.
Yes, you should wrap Web service call in try-catch. DON'T use empty catch as they (mostly) are pure evil. Your catch block should at least log exception. I don't know about your applications logic, but probably some message (like "information from service wasn't fetched because of tech error") should be shown to user.
It's ok, but try to just catch exception types that you can handle.
Avoid catching any "Exception" or, if you do so, log and/or alert the user and/or retry to call the webservice.
If it's a windows forms app I usually wrap the last "Exception" catch in an #if DEBUG block to avoid hiding exceptions while debugging or testing.
#if !DEBUG
catch (Exception ex)
{
// show messagebox, log, etc
}
#endif
this is a case that could result in an exception being thrown, so yes it should be wrapped on a try catch block.
What to do with the exception handler it depends on the program logic...
Putting a web service method in a try catch block is a good idea,as you stated you do not want to crash the calling application because something went wrong in the web service method.
Additionally, rather than throw an exception back to the client, who can't do anything about it anyway, you may consider having all of your web service methods return a structure or small class that can contain the status of the call, an error code and an friendly message that could explain the error.
using System;
using System.ServiceModel;
using Entities; //my entities
using AuthenticationService; //my webservice reference
namespace Application.SL.Model
{
public class AuthenticationServiceHelper
{
/// <summary>
/// User log in
/// </summary>
/// <param name="callback"></param>
public void UserLogIn(Action<C48PR01IzhodOut, Exception> callback)
{
var proxy = new AuthenticationServiceClient();
try
{
proxy.UserLogInCompleted += (sender, eventargs) =>
{
var userCallback = eventargs.UserState as Action<C48PR01IzhodOut, Exception>;
if (userCallback == null)
return;
if (eventargs.Error != null)
{
userCallback(null, eventargs.Error);
return;
}
userCallback(eventargs.Result, null);
};
proxy.UserLogInAsync(callback);
}
catch (Exception ex)
{
proxy.Abort();
ErrorHelper.WriteErrorLog(ex.ToString());
}
finally
{
if (proxy.State != CommunicationState.Closed)
{
proxy.CloseAsync();
}
}
}
}
Is this a good practice or is there room for improvement?

Resources