I've seen the Index.search method raise a search.TransientError, and I know other methods may raise such errors as well, but in the documentation, I'm seeing code like this:
# Index the document.
try:
index.put(doc)
except search.PutError, e:
result = e.results[0]
if result.code == search.OperationResult.TRANSIENT_ERROR:
# possibly retry indexing result.object_id
except search.Error, e:
# possibly log the failure
When are checks like this necessary, and in which cases can I rely on search.TransientErrorbeing raised?
Looking through the source code, it looks like some (if not all) methods of the Index class use the _MakeSyncSearchServiceCall function, which, if anything goes wrong, calls _ToSearchError passing in an exception. This error returns an element from the _ERROR_MAP dictionary, based on the application_error property of the error. This dictionary contains theTransientError`, so it is clear that it is raised in certain cases.
So, when is it necessary to check result.code, and what other errors could be raised in cases that are out of my control?
Related
Eiffel Studio seems to pass through my requirements even if I have them enabled on project settings. And as far as I remember I was able some time to put a break point into the requirements...
I don't understand what I'am missing here, as you can see in my example, the requirement passes through as I have the same condition on the code and it goes into (attached {POWER_DEVICE} a_csv.device as l_dev).
A general rule for inherited assertions is the following:
preconditions can be only relaxed;
postconditions can be only strengthened.
In the particular example the effective precondition is
True
or else
valid_csv (a_csv) and then attached {POWER_DEVICE} a_csv.device
This is reflected by the keywords require at the beginning and require else in the middle of the combined precondition in the flat form of the feature. The expression True is inherited. This is the precondition of the feature in the parent.
A possible solution is to move valid_csv (a_csv) to the parent feature, and redefine valid_csv in the descendant. If valid_csv is common for all calls, but the second test varies across descendants, it might be better to introduce a new feature is_known and have 2 precondition subclauses in the parent:
is_valid_csv: is_valid_csv (a_csv)
is_known_csv: is_known_csv (a_csv)
The implementation of is_known_csv in the class POWER_CSV_PROCESSOR would be
is_known_csv (a_csv: ...)
do
Result := attached {POWER_DEVICE} a_csv.device
end
and the precondition of feature process in POWER_CSV_PROCESSOR would be empty.
The caller would then do something like
if processor.is_known_csv (csv) then
processor.process (csv)
end
What's the point of throwing exceptions?
For example I stumbled across this:
static List<Integer> list(int [] a) {
if (a == null)
throw new NullPointerException();
//...
But when you don't throw the nullpointer, you'll also get a nullpointer?
I see this regularly and I wanted to know if this is a good habit to learn?
It's better to fail fast. For example the function could do a bunch of stuff before it even references the variable "a" in your example resulting in a lot of unnecessary processing.. It would be best just to fail immediately if you know "a" is null from the very beginning. You could also append a custom error message to the exception as well.
The idea behind the THROW is to prevent the error from stopping your program.
If it's a fatal enough error, your program will stop anyway. But if the program can continue it will, and just let you know that an error occurred.
In many cases, you assign a function to report the error, since you threw it up and know what it is.
I always found throwing exceptions to be a matter of design and readability. For example, generally when I design something I prefer to handle errors where they occur. However an equally valid design would be to throw the exception and handle it somewhere else. I have seen some abstractions where generally your flow is something similar to this...
FlowControl -> GenericMethod(catches exceptions and calls methods only) -> PrivateMethods (generally used to do the work, throws exceptions).
You might find a more complete answer here as well: When to catch the Exception vs When to throw the Exceptions?
It's possible that the rest of your method will not throw the exception and will instead have some kind of undesirable behavior if you use a null pointer. In your example, if it's basically a "ToList" wrapper, it might be implemented as:
static List<Integer> list(int[] a)
{
List<int> ret = new List<int>();
foreach (int i in a)
ret.add(i);
return ret;
}
Instead of throwing, this will simply return an empty list (if I recall correctly at least, I don't think C# throws on null lists used in foreach). As such, you'll need to include an explicit null check and throw to get your desired behavior.
Throwing specific exception means that your application has faced something it shouldn't have. It can be either invalid argument(when someone passes null and current method cannot work with value of null), invalid field state(its value has been changed to some value, which is forbidden for instance current state) and many many more.
Basically when you throw exceptions in a good manner, each person using your e.g. library can preserve its correct flow.
So I am doing a simple personal project in winforms with F#. My code used to work, but now throws this exception for seemingly no reason.
An unhandled exception of type 'System.InvalidOperationException' occurred in FSharp.Core.dll
Additional information: The initialization of an object or value resulted in an object or value being accessed recursively before it was fully initialized.
The code is a member method that is being invoked from the constructor of the form itself
do
//lots of other constructor code before this point
// render the form
form.ResumeLayout(false)
form.PerformLayout()
form.ReloadGoals
//several other members before here
member form.ReloadGoals =
let x = 10 //crashes on this line
The website where I grabbed the template for the project I am using is this one.
Unfortunately I have made some substantial additions to this.
I would be glad to post more code, but I need to know what code would be relevant exactly, as I am not exactly sure and don't want to bog down the post in extraneous code.
Also I can't really find a lot of documentation on System.InvalidOperationException.
Every time I find it, it is being used as an example of an exception you can throw on your own, not what causes it.
See The F# 3.0 Language Specification (final version, PDF), ยง8.6.1 Primary Constructors in Classes:
During construction, no member on the type may be called before the last value or function definition in the type
has completed; such a call results in an InvalidOperationException.
Almost certainly, your code in the question doesn't tell the full story. If you hit the above
mentioned restriction, then there's somewhere an attempt to access a field or member not fully initialized.
Some example:
type X() as this =
let x = this.X
member __.X = 42
X()
One workaround might be to encapsulate the offending code in a member of its own and call that in the constructor instead. Another would be the wrapping in a function definition.
This will be an incomplete answer, since I cannot reproduce the problem (using F# interactive, the given example, the ReloadGoals modification, and Form.Show, the code runs fine). However, there are strange things happening:
Taken from the template, there should be a handler method for the Form.Load event, which fires when the type is fully constructed. Why is additional loading code in the constructor instead of this event handler? Load exists precisely to counter this kind of problem with unorderly initialization.
The template you are using isn't exactly sane F#. For example, initControls is a value of type unit that is evaluated where it is defined; its binding to a name is absolutely useless and should be replaced with a simple do. Writing initControls in the do block later has no effect at all. form.ResumeLayout(false); form.PerformLayout() should be equivalent to form.ResumeLayout(true), but I don't understand what these are doing in the constructor in the first place. The event handlers have two possibly unnecessary indirections: one to a delegate constructor, another to a method that has no real reason to exist -- the handlers should be lambdas or simple, private functions. Why are they public members?!
The error appearing in the question is probably caused by the usage of form in its own constructor. Move your new usage to the Load event handler, and it should work.
Personally, I would go further and ditch implementation inheritance by instantiating a plain Form and subscribing to its events. For example, in FSI, something similar to the template could be done like this:
open System.Drawing
open System.Windows.Forms
let form = new Form()
form.ClientSize <- new Size(600, 600)
form.Text <- "F# Form"
let formLabel = new Label()
formLabel.Text <- "Doubleclick test!"
formLabel.DoubleClick.Add <| fun _ -> form.Close()
form.Controls.Add(formLabel)
form.Show()
which uses no inheritance at all. (In an application, you'd use Application.Run etc instead of form.Show().) This does not run into initialization problems as easily and, additionally, is very useful if you want to encapsulate the form inside a simpler type or even just a function.
So I have seen this error show up, just sometimes, but it is not helpful in describing the actual error which has occured. Nor does it give any clues as to what might cause it to display.
Cannot use modParams with indexes that do not exist.
Can anyone explain more verbosly what this error means, what it relates to (such as a behaviour, component, controller, etc), the most common causes and how to fix it?
To kickstart the investigation, you can find the error here.
https://github.com/cakephp/cakephp/blob/master/lib/Cake/Utility/ObjectCollection.php#L128
Layman's Terms
CakePHP is being told to apply an array of parameters to a collection of objects, such that each particular object can modify the parameters sent on to the next object. There is an error in how CakePHP is being told to do this.
In Depth
Generically, this rises from the CakePHP event publication mechanism. Somewhere in your code is an instance of ObjectCollection, which is being triggered with certain parameters. That is, a method is being called on every object in that collection.
Each callback method is given parameters. Originally the parameters are passed into trigger(). In normal cases (where modParams is false), every callback gets the same parameters. But when modParams is not strictly false, the result of each callback overwrites the parameter indicated by modParams.
So if there are two objects in the collection, modParams is 1, and the params[1] is 'a' initially, then the callback is given the first object with params[1] == a. That callback returns 'b', so when the next callback is called, the second object gets params[1] == b.
The exception raises when the modParams value given does not exist in the originally given params. Eg, if modParams is 2 and params is array (0 => 'a', 1 => 'b'), you'll get this exception.
In your case
Specifically, debugging this has to be done at a low-level because it's a method on a generic class. The backtrace from the Exception should get you bubbled up to a trigger() call on a particular concrete class. That call is being given non-false modParams and a params that doesn't have the given modParams. It could be a code bug in a concrete class extending ObjectCollection, or it could simply be a generic message arising from a method not being given expected arguments.
Have you tried reading the documentation?
/*
* - `modParams` Allows each object the callback gets called on to modify the parameters to the next object.
* Setting modParams to an integer value will allow you to modify the parameter with that index.
* Any non-null value will modify the parameter index indicated.
* Defaults to false.
*/
You did not paste any code, so I guess your 3rd arg of the method contains something wrong.
I would like to understand EasyMock better, and working with it I came up with this question.
What I would like to do is setting up a negative expectation over an object, to check if a certain method is not called during the test (when verifying those initial expectations).
I know that the default behaviour of verify is checking both cases: your expectations were met, and no other calls were performed; but there is no record in the test that a certain method is not called, in other words, if you set an expectation over this method and it doesn't get called, your test will fail (confirming that your implementation is behaving properly!).
Is there a way using EasyMock to set this up? I couldn't find anything in the documentation.
Thank you for your attention, and in advance for your help!
The way EasyMock works is like this:
create a Mock Object for the interface you would like to simulate,
record the expected behavior, and
switch the Mock Object to replay state.
Like in following if you don't set any expectation:
mock = createMock(YourInterface.class); // 1
// 2 (we do not expect anything)
replay(mock); // 3
then it means that if ClassUnderTest call any of the interface's methods, the Mock Object will throw an AssertionError like this:
java.lang.AssertionError:
Unexpected method call yourMethodWhichYouDidNotExpectToBeCalled():
This itself is Negative Expectation checking.