Handle exception in asp.net mvc controller - c#

I've create new attribute and in the logic I've some exception
My question is: how should I handle it in the controller and pass it to the view?
In the code below I throw the exception, how should I move it to the view?
This is the attribute in the controller
[HttpPost]
[CheckToken]
public JsonResult Edit(Roles role)
{
...
}
This is the attribute
public class CheckToken : FilterAttribute, IAuthorizationFilter
{
....
catch (HttpAntiForgeryException e)
{
throw new HttpAntiForgeryException("token not found");
}
}

From the book CLR Via C#, there is an advice on exceptions handling:
Don’t CatchEverything
A ubiquitous mistake made by developers who
have not been properly trained on the proper use of
exceptions is to use catchblocks too often and
improperly. When you catch an exception, you’re stating that you
expected this exception, you understand why it occurred, and you know
how to deal with it.
We should catch exceptions only when we know how to recover our application state from that exception.
In your code, you catch the exception without doing anything than just re-throwing it. This is just not necessary. And be aware that when you re-throw the exception, the CLR resets its starting point for the exception.
catch (HttpAntiForgeryException e)
{
throw new HttpAntiForgeryException("token not found"); // CLR thinks this is where exception originated.
}
In your case, I would not handle the exception and pass it to the view. I will just let the execution stop and handle it inside a global exception filter to return an error to the user with correct http status code (for example: we should not return an error page with status 200) and may optionally log an error to DB for further analysis.
For information how to implement global exception filter: http://forums.asp.net/t/1848242.aspx?How+to+implement+global+error+handling+in+ASP+NET+Web+API

Instead of throwing exception..u can do like as :-
catch (HttpAntiForgeryException e)
{
filterContext.RouteData.Values.Add("Antiforgery", "token not found");
}
and use Routevalues in ur jsonresult as :
[HttpPost]
[CheckToken]
public JsonResult GroupEdit(Roles role)
{
ViewData["Message"] = RouteData.Values["Antiforgery"];
}

Related

How to Throw Multilingual Exceptions

I have a multilingual web application, where I use a resource file in the frontend to display the different text.
I followed this approach http://www.codeproject.com/Tips/586948/ASP-NET-Website-and-Csharp-with-Multi-Language
Is there a way where the exception handling done in the backend throws exceptions according to the current language selected?
You need CustomException which inherit Exception for this.(Be aware never catch all the exceptions only the exception needed for your case, I just wrote you an example. If you catch all the exception you can lose specific information when something go wrong on productive server. Like I said in the past I used it for DBConcurrencyException)
Business Object logic
try
{
//some code
}
catch(Exception ex)
{
CustomException newEx = new CustomException();
newEx.Message = "Translate Multilanguage String depending of the user culture"
throw newEx;
}
UI-part aspx.Page
try
{
//some code which calls the BO logic with try/catch
}
catch(CustomException ex)
{
Label1.Text = ex.Message;
}
How to use this for validation purpose:
if(myValue < 5)
throw new CustomException("Value should not be under 5");

Log exceptions handled in try..catch with Elmah

I'm trying to log with Elmah exceptions handled in try...catch blocks.
I have added a global handle error filter on Global.axax:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ElmahHandledErrorLoggerFilter());
filters.Add(new HandleErrorAttribute());
}
This is my ElmahHandledErrorLoggerFilter:
public class ElmahHandledErrorLoggerFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
if (context.ExceptionHandled)
ErrorSignal.FromCurrentContext().Raise(context.Exception);
}
}
It will only log the Exception as in try{ ... }catch{ throw new Exception(); }. But that's not the problem, the problem is that I have a method with a try-catch called from the code already inside another try-catch. In this case although I put throw new Exception() inside the catch of the inner-method it doesn't log the exception, it goes back to the catch in the first method without logging the Exception. For example:
public void MainMethod()
{
try
{
SecondMethod();
}
catch
{
....second method jump here.....
}
}
public void SecondMethod()
{
try
{
int a =0;
int b =;
int result = b/a;
}
catch
{
throw new Exception();
}
}
The exception thrown by SecondMethod is not being logged by Elmah. It goes back to the main method catch. If the main method catch also has a throw new Exception() code then it logs the exception. However it will be logged with the stack trace pointing to MainMethod and not to the SecondMethod.
What I wanted what was that every time it reaches a catch without rethrowing a new Exception, Elmah would log the exception. This is because I have many try-catch blocks in my application and I want to log these exceptions without manually logging on each try-catch. However if you tell me how can I log the exception from SecondMethod that would be fine.
Are you using ASP MVC?
The filters will only execute for unhandled exceptions thrown from the controller methods. (The context.ExceptionHandled property tells you if it has been handled by another filter, not in a try-catch block). So if you swallow the exceptions in try-catch blocks inside your methods then they will not be handled by the error filters.
You need to decide when you want to manually handle the exceptions inside your code using try-catch blocks (and in that case manually log the exceptions with the aid of a base controller class or a helper class) or let the exception bubble and be handled by your filters. (You probably will want a mixture of the two, depending on each particular use case)
When you decide to rethrow the exceptions, take a look at this SO question. Basically you can rethrow an exception preserving the stack trace with:
try
{
//code
}
catch (Exception ex)
{
//...some error handling code here...
//Otherwise why the try-catch at all?
throw;
}
You could do that in your sample MainMethod and the exception logged would preserve the stack trace.

Catching exceptions for displaying info

I have setup so that if an Exception is thrown I can display it with my custom error page. But in some cases I don't want to be navigated to the error page, but want it to display a simple dialog window.
public ActionResult Page1()
{
//The custom error page shows the exception, if one was thrown
throw new Exception( "An exception was thrown" );
return View();
}
public ActionResult Page2()
{
//A dialog should show the exception, if one was thrown
try
{
throw new Exception( "An exception was thrown" );
}
catch( Exception ex )
{
ViewData["exception"] = ex;
}
return View();
}
Is it possible to have a CustomAttribute to handle an exception which has been thrown in an Controller action? If I added CatchException to Page2, can I automate the process of storing the exception in the ViewData, each time an exception was thrown. I don't have much experience of CustomAttributes and I'd be much appreciated if you could help me.
The Page2 example works perfectly fine, I just want to make the code cleaner as it isn't really pretty to have try catches in every action (where I want to show a dialog).
I am using .NET MVC 4.
You can create a base controller that catch the exceptions and handle it for you.
Also, looks like the Controllers already have a mechanism to do that for you. You'll have to override the OnException method inside the controller. You can get a good example here:
Handling exception in ASP.NET MVC
Also, there's another answer on how to use the OnException here:
Using the OnException
By using that, your code will be cleaner, since you will not be doing a lot of try/catch blocks.
You'll have to filter the exception you wanna handle. Like this:
protected override void OnException(ExceptionContext contextFilter)
{
// Here you test if the exception is what you are expecting
if (contextFilter.Exception is YourExpectedException)
{
// Switch to an error view
...
}
//Also, if you want to handle the exception based on the action called, you can do this:
string actionName = contextFilter.RouteData.Values["action"];
//If you also want the controller name (not needed in this case, but adding for knowledge)
string controllerName = contextFilter.RouteData.Values["controller"];
string[] actionsToHandle = {"ActionA", "ActionB", "ActionC" };
if (actionsTohandle.Contains(actionName))
{
//Do your handling.
}
//Otherwise, let the base OnException method handle it.
base.OnException(contextFilter);
}
You can create subclass of Exception class, and catch it in your Page 2
internal class DialogException : Exception
{}
public ActionResult Page2()
{
//This should a dialog if an exception was thrown
try
{
//throw new Exception( "An exception was thrown, redirect" );
throw new DialogException( "An exception was thrown, show dialog" );
}
catch( DialogException ex )
{
ViewData["exception"] = ex;
}
return View();
}

How to catch the original (inner) exception in C#?

i'm calling a function that throws a custom exception:
GetLockOwnerInfo(...)
This function in turn is calling a function that throws an exception:
GetLockOwnerInfo(...)
ExecuteReader(...)
This function in turn is calling a function that throws an exception:
GetLockOwnerInfo(...)
ExecuteReader(...)
ExecuteReader(...)
And so on:
GetLockOwnerInfo(...)
ExecuteReader(...)
ExecuteReader(...)
ExecuteReaderClient(...)
Fill(...)
One of these functions throws an SqlException, although that code has no idea what an SqlException is.
Higher levels wrap that SqlException into another BusinessRuleException in order to include some special properties and additional details, while including the "original" exception as InnerException:
catch (DbException ex)
{
BusinessRuleExcpetion e = new BusinessRuleException(ex)
...
throw e;
}
Higher levels wrap that BusinessRuleException into another LockerException in order to include some special properties and additional details, while including the "original" exception as InnerException:
catch (BusinessRuleException ex)
{
LockerException e = new LockerException(ex)
...
throw e;
}
The problem now is that i want to catch the origianl SqlException, to check for a particular error code.
But there's no way to "catch the inner exception":
try
{
DoSomething();
}
catch (SqlException e)
{
if (e.Number = 247)
{
return "Someone";
}
else
throw;
}
i thought about catching SqlException right when it's thrown, and copy various values to the re-thrown exception - but that code is not dependant on Sql. It is experiencing an SqlException, but it has no dependency on SqlException.
i thought about catching all exceptions:
try
{
DoSomething(...);
}
catch (Exception e)
{
SqlException ex = HuntAroundForAnSqlException(e);
if (ex != null)
{
if (e.Number = 247)
{
return "Someone";
}
else
throw;
}
else
throw;
}
But that's horrible code.
Given that .NET does not let you alter the Message of an Exception to include additional information, what is the intended mechanism to catch original exceptions?
You need c# 6 / visual studio 2015 in order to do this using a predicate:
catch (ArgumentException e) when (e.ParamName == “…”)
{
}
Official C# Try/Catch Documentation
I hate to have to tell you this, but you cannot catch an inner exception.
What you can do is inspect one.
I suggest you catch your high-level exception (I believe it was LockerException) and inspect the InnerException property of that exception. Check the type, and if it's not a SqlException, check the InnerException of that exception. Walk each one until you find a SqlException type, then get the data you need.
That said, I agree with dasblinkenlight that you should consider -- if possible -- a heavy refactor of your exception framework.
Checking the error code of a wrapped exception is not a good practice, because it hurts encapsulation rather severely. Imagine at some point rewriting the logic to read from a non-SQL source, say, a web service. It would throw something other than SQLException under the same condition, and your outer code would have no way to detect it.
You should add code to the block catching SQLException to check for e.Number = 247 right then and there, and throw BusinessRuleException with some property that differentiates it from BusinessRuleException thrown in response to non-SQLException and SQLException with e.Number != 247 in some meaningful way. For example, if the magic number 247 means you've encountered a duplicate (a pure speculation on my part at this point), you could do something like this:
catch (SQLException e) {
var toThrow = new BusinessRuleException(e);
if (e.Number == 247) {
toThrow.DuplicateDetected = true;
}
throw toThrow;
}
When you catch BusinessRuleException later, you can check its DuplicateDetected property, and act accordingly.
EDIT 1 (in response to the comment that the DB-reading code cannot check for SQLException)
You can also change your BusinessRuleException to check for SQLException in its constructor, like this:
public BusinessRuleException(Exception inner)
: base(inner) {
SetDuplicateDetectedFlag(inner);
}
public BusinessRuleException(string message, Exception inner)
: base(message, inner) {
SetDuplicateDetectedFlag(inner);
}
private void SetDuplicateDetectedFlag(Exception inner) {
var innerSql = inner as SqlException;
DuplicateDetected = innerSql != null && innerSql.Number == 247;
}
This is less desirable, because it breaks encapsulation, but at least it does it in a single place. If you need to examine other types of exceptions (e.g. because you've added a web service source), you could add it to the SetDuplicateDetectedFlag method, and everything would work again.
Having an outer application layer care about the details of a wrapped exception is a code smell; the deeper the wrapping, the bigger the smell. The class which you now have wrapping the SqlException into a dbException is presumably designed to expose an SqlClient as a generic database interface. As such, that class should include a means of distinguishing different exceptional conditions. It may, for example, define a dbTimeoutWaitingForLockException and decide to throw it when it catches an SqlException and determines based upon its error code that there was a lock timeout. In vb.net, it might be cleaner to have a dbException type which exposes an ErrorCause enumeration, so one could then say Catch Ex as dbException When ex.Cause = dbErrorCauses.LockTimeout, but unfortunately exception filters are not usable in C#.
If one has a situation where the inner-class wrapper won't know enough about what it's doing to know how it should map exceptions, it may be helpful to have the inner-class method accept an exception-wrapping delegate which would take an exception the inner class has caught or would "like" to throw, and wrap it in a way appropriate to the outer class. Such an approach would likely be overkill in cases where the inner class is called directly from the outer class, but can be useful if there are intermediate classes involved.
Good question and good answers!
I just want to supplement the answers already given with some further thoughts:
On one hand I agree with dasblinkenlight and the other users. If you catch one exception to rethrow an exception of a different type with the original exception set as the inner exception then you should do this for no other reason than to maintain the method's contract. (Accessing the SQL server is an implementation detail that the caller is not/must not/cannot be aware of, so it cannot anticipate that a SqlException (or DbException for that matter) will be thrown.)
Applying this technique however has some implications that one should be aware of:
You are concealing the root cause of the error. In your example you are reporting to the caller that a business rule was invalid(?), violated(?) etc., when in fact there was a problem accessing the DB (which would be immediately clear if the DbException were allowed to bubble up the call stack further).
You are concealing the location where the error originally occurred. The StackTrace property of the caught exception will point to a catch-block far away from the location the error originally occurred. This can make debugging notoriously difficult unless you take
great care to log the stack traces of all the inner exceptions as well. (This is especially true once the software has been deployed into production and you have no means to attach a
debugger...)
Given that .NET does not let you alter the Message of an Exception to include additional information, what is the intended mechanism to catch original exceptions?
It is true that .NET does not allow you to alter the Message of an Exception. It provides another mechanism however to supply additional information to an Exception via the Exception.Data dictionary. So if all you want to do is add additional data to an exception, then there is no reason to wrap the original exception and throw a new one. Instead just do:
public void DoStuff(String filename)
{
try {
// Some file I/O here...
}
catch (IOException ex) {
// Add filename to the IOException
ex.Data.Add("Filename", filename);
// Send the exception along its way
throw;
}
}
As other peeps say, you cannot catch an the InnerException. A function such as this could help you get the InnerException out of the tree though:
public static bool TryFindInnerException<T>(Exception top, out T foundException) where T : Exception
{
if (top == null)
{
foundException = null;
return false;
}
Console.WriteLine(top.GetType());
if (typeof(T) == top.GetType())
{
foundException = (T)top;
return true;
}
return TryFindInnerException<T>(top.InnerException, out foundException);
}
I agree with the other comments that this is a code smell 🦨 and should be avoided. But if a refactor is not possible you could try something like this...
Create an extension method...
public static bool HasInnerException(this Exception ex, Func<Exception, bool> match)
{
if (ex.InnerException == null)
{
return false;
}
return match(ex.InnerException) || HasInnerException(ex.InnerException, match);
}
And use it like...
catch (Exception ex) when (ex.HasInnerException(e => e is MyExceptionThatIsHidden))
{
...
But really you should be solving for 👇
var exception = new Exception("wrapped exception 3",
new Exception("wrapped exception 2",
new Exception("wrapped exception 1",
new MyExceptionThatIsHidden("original exception")))); // <--- ???

Programmatically suppressing exceptions in C#

I have the following try-catch statement and I do not want to not throw the exception if the message property contains 'My error' in the text.
How can I programmatcially accomplish this? Also, would this be considered code-smell?
try
{
}
catch(Exception e)
{
if(e.Messages.Contains("My error"))
{
//want to display a friendly message and suppress the exception
}
else
{
throw e;
}
}
You shouldn't catch errors based on the error test. You should make your own exception class that extends exception:
class MyErrorException : Exception { }
and throw and catch those. (Excuse my syntax if it's wrong, I haven't done C# in a while).
That being said, throwing and catching your own Exceptions instead of propagating them is perfectly normal, and it is how you actually should do exception handling.
You should be catching the specific exception you're looking for. Quite frankly, that code is shocking. You should have something like ...
public class MyCoolException : Exception {
public MyCoolException(string msg) : base(msg) {}
}
public void MyCoolMethod() {
// if bad things happen
throw new MyCoolException("You did something wrong!");
}
Then later in your code you can use it like ...
try {
MyCoolMethod();
} catch (MyCoolException e) {
// do some stuff
}
Your code creates maintainability issues because a simple text change can have strange side effects. You can have your own exception class which inherits from System.Exception. Then instead of having an if you could do the following:
try
{
}
catch(MyException myException) //or just catch(MyException)
{
//display a friendly message
}
also you don't want to do throw e because it doesn't preserver the Stack, just throw; will do.
When I throw Exception rather than a derived class I always mean a failed assertion. I don't like failing out the backend because we are still able to receive a request (just not that one again). If we're really toast it will just error out on the next request anyway.
When the back end needs to generate an error message I have a ErrorMessage class that inherits from Exception and takes ErrorMessage and ErrorMessageTitle as constructor arguments.

Categories