F# exception and inner exception property - f#

in F# i can declare a custom exception like so:
exception Foo of string,
which will map the string to the Message property.
how do I declare one that I can later use to raise a caught exception as the inner exception of this one? In other words, how do i do something like (pseudo)
try
...
with e -> raise Foo (message, innerException) where innerException is e?
Thanks!

The simple declaration of exceptions using exception is limited in many ways. If you want to use other features of standard .NET exceptions (i.e. inner exception), then you can declare exception as a class:
open System
type FooException(message:string, innerException:Exception) =
inherit Exception(message, innerException)
You can also provide overloaded constructors, for example if you want to use null as a default value for InnerException.
The exception can be raised as an ordinary .NET exception using raise:
raise (new FooException(message, e))

Related

dart: how to catch TypeError during compilation

Below code throws a runtime error.
TypeError: Instance of 'FormatException': type 'FormatException' is not a subtype of type 'CustomException'
Why Test(e) does not fail at compilation as type of e is Exception and expected is CustomException. How to enforce it so one cannot pass Exception there.
abstract class CustomException implements Exception {
String get code;
}
class Test {
final CustomException ex;
Test(this.ex);
}
void main() {
try {
throw new FormatException();
} on Exception catch (e) {
final t = Test(e);
print('message: $t');
}
}
Dart has (for now) implicit downcasts from a supertype to a subtype. You are allowed to use an expression which is a super-type of the actual type that is required, under the assumption that you know what you are doing.
Here you have a value with static type Exception (the e that was caught), and you pass it to a constructor requiring a CustomException, which is a subtype of Exception.
The language allows this, but inserts a run-time downcast (equivalent to e as CustomException). That cast fails because the value is actually a FormatException.
With the up-coming null safety feature, implicit downcasts will be removed except from dynamic (because dynamic turns off static type checks anyway). When that happens, the Test(e) invocation becomes invalid. Until then, this code compilers and fails at run-time.
Until then, you can get the analyzer to warn you about implicit calls by configuring it in the analysis_options.yaml file

Handle exceptions thrown by F# type provider in FSX script

I have an FSX script which includes a type provider. When the script is run, I would like to show a user-friendly message when the type provider throws an exception. (For example, when the SqlDataProvider cannot connect to the database.)
Is that possible?
This obviously won't work, but illustrates the idea:
type Sql =
try
SqlDataProvider< DatabaseVendor = databaseVendor, ConnectionString = connectionString, TableNames = tableNames >
with ex ->
printfn "Cannot connect to the database."
Here is a gist that can be used to test potential solutions.
When the script runs, the exception will be thrown, but not until you use or instantiate the type from the Type Provider.
In your case, you wouldn't wrap the definition of the type in a try, but rather the usage:
type Sql = SqlDataProvider<...>
// When you go to _use_ the type, handle exceptions:
try
let ctx = Sql.GetDataContext ()
// .. use
with
| :? SomeExceptionType as ex -> printfn "Cannot connect to the database."

XNA Shadow mapping - invalid model?

I try to use shadow mapping sample from http://xbox.create.msdn.com/en-US/education/catalog/sample/shadow_mapping_1.
When I try to load my model there is an exception in:
effect.CurrentTechnique = effect.Techniques[techniqueName];
in DrawModel method.
An unhandled exception of type 'System.ArgumentNullException' occurred in Microsoft.Xna.Framework.Graphics.dll
Additional information: This method does not accept null for this parameter.
What can be wrong with my model?
Check that your techniqueName variable isn't null.
I'm betting effect.Techniques[null] throws a System.ArgumentNullException for the same reason Dictionary.Item does.

How can I inject IPrincipal using TinyIoC?

This line:
container.Register<IPrincipal>().UsingConstructor(() => HttpContext.Current.User);
throws the following exception:
Cannot register type System.Security.Principal.IPrincipal - abstract
classes or interfaces are not valid implementation types for
SingletonFactory.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details:
Tss.Rhnncp.DietPlanner.Bootstap.TinyIoCRegistrationTypeException:
Cannot register type System.Security.Principal.IPrincipal - abstract
classes or interfaces are not valid implementation types for
SingletonFactory.
Source Error:
Line 2663: throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory");
Line 2664:
Line 2665: if (!IsValidAssignment(registerType, registerImplementation))
Line 2666: throw new TinyIoCRegistrationTypeException(registerImplementation, "SingletonFactory");
Line 2667:
I'm not familiar with TinyIoc, but I expect you need something like this:
container.Register<IPrincipal>(() => HttpContext.Current.User);

Why isn't my own Exception derived type recognised by Elmah?

I've just implemented Elmah for logging in my MVC3 app, and of course all is well, except that when I use signalling to log a custom exception, Elmah seems to 'see' the InnerException property of my custom exception, but not the custom exception itself.
When I use the code below to signal the exception, instead of seeing, "CtsDataException: Error" in my error log, as I would expect, I see, "DbEntityValidation: Validation failed for one or more entities.", the inner exception and its message. If I open the log item, I see that my custom exception has correctly been logged, so it looks like the 'exception descriptor' is wrong, not the actual log entry.
What am I doing wrong?
PS, my custom exception is as such:
public class CtsDataException: Exception
{
public CtsDataException(string message, Exception innerException): base(message, innerException)
{
ValidationResults = new List<CtsDbValidationResult>();
var vex = innerException as DbEntityValidationException;
if (vex != null)
{
ValidationResults = vex.EntityValidationErrors.Select(e => new CtsDbValidationResult(e)).ToList();
}
}
public IEnumerable<CtsDbValidationResult> ValidationResults { get; set; }
}
The signalling code looks like this:
protected void HandleDbEntityValidationException(DbEntityValidationException vex, string message)
{
var ctsEx = new CtsDataException(message, vex);
ErrorSignal.FromCurrentContext().Raise(ctsEx);
}
HandleDbEntityValidationException is on my base controller. It is invoked in derived controllers like this:
catch (DbEntityValidationException vx)
{
var msg = string.Format("Error updating employee '{0}'", entity.RefNum);
HandleDbEntityValidationException(vx, msg);
}
I've done some of my own testing and come to the conclusion that it's not ELMAH choosing to report only the InnerException. If you take a look at the details for the error and then click Original ASP.NET error page, you'll see that the original yellow screen that occurred will list the Exception Details as the InnerException and not the primary custom exception thrown. The stack trace further shows the original custom exception that was thrown instead. This is the information ELMAH is using in logging the error.
My testing consisted of creating a CustomException class that did nothing more than inherit from Exception. I then simply called:
throw new CustomException("error!", new NullReferenceException());
... and what got reported was the NullReferenceException with CustomException only appearing in the Stack Trace.
My theory of choice in this scenario is that ELMAH is choosing to display the exception that was thrown rather than the exceptions used to wrap it. If ELMAH had a way to include a message with the log, I think this "wrap in a more descriptive but ultimately irrelevant exception that is never thrown" malarkey could end.
I realize that I'm a few years late to actually answer the original question on time, but for others trying to achieve what I think was the OP's intention, I came across a bit of smartness in the LibLog package for Hangfire (slightly adapted):
var _errorType = Type.GetType("Elmah.Error, Elmah");
dynamic error = Activator.CreateInstance(_errorType, originalException);
error.Message = "Your custom message";
error.Type = "Error"; // Or type of original exception or ...
error.Time = DateTime.Now;
Elmah.ErrorLog.GetDefault(null).Log(error);

Resources