Multiple exception map - exception

I have to create a a new exception (MultipleErrorException) which extends MySuperException class. I have another exception (SingleErrorException) which also extends MySuperException.
Looking at the pseudo code below:
for (a number of times)
try
call myMethod(myObject) that throws SingleErrorException
catch(SingleErrorException e)
add the caught SingleErrorException object to a
MultipleErrorException object where a mapping should
be created mapping myObject to SingleErrorException
I need to throw a single "MultipleErrorException" which holds a map (myObject-->SingleErrorExceptions).
Is there any other way to this rather than creating an initial MultipleErrorException object before the for loop, an then adding the mappings as the exceptions are caught?
Thanks

java.lang.Exception as such does not have any method to support your requirement.
If you need it, then one way is to add the Map variable in MultipleErrorException and setting the value of it, but again, editing the exception object is not good.
Instead, you can add the error messages to Map and return the map instead of throwing the exception from the method.

Related

Mockito: use InOrder with spy object

I want to check the invocation order of some methods using mockito. One of the methods I want to check is on a mock, the other one is in the real class that I am testing, so I am using a spy object for checking that:
However, mockito is only aware about calls on the mock methods, but not on the spy object:
MigrationServiceImpl migrationServiceSpy = spy(migrationServiceImpl);
// I have tested without no more configuraitons on the spy, and also with the following
// by separate (one by one)
// I tried this:
doNothing().when(migrationServiceSpy).updateCheckpointDate(eq(migration), any(Instant.class)); // In this case the call is not tracked by InOrder
// And this:
when(migrationServiceSpy.updateCheckpointDate(eq(migration), any(Instant.class))).thenReturn(true); // In this case the call is not tracked by InOrder
// And this:
when(migrationServiceSpy.updateCheckpointDate(eq(migration), any(Instant.class))).thenCallRealMethod(); // This line is throwing a null pointer exception but I don't understand why, since if I do not spy the real object it works without failing.
//Here I call the real method
migrationServiceImpl.updateStatus(DEFAULT_MIGRATION_ID, inProgressStatus);
InOrder inOrder = inOrder(migrationServiceSpy, mongoMigrationRunner);
inOrder.verify(migrationServiceSpy).updateCheckpointDate(any(Migration.class), any(Instant.class));
inOrder.verify(mongoMigrationRunner).runMigrationForInterval(any(Migration.class), anyString(), any(Instant[].class));
What can I do? What's hapenning?
The solution was to make the call on the spy object instead the real object:
migrationServiceSpy.updateStatus(DEFAULT_MIGRATION_ID, inProgressStatus);
instead of:
migrationServiceImpl.updateStatus(DEFAULT_MIGRATION_ID, inProgressStatus);

Test Failure Message in mockito : Argument(s) are different! Wanted:

I am testing a Restful endpoint in my JUnit and getting an exception as below in the
list which is present as an argument inside the save method,
**"Argument(s) are different! Wanted:"**
save(
"121",
[com.domain.PP#6809cf9d,
com.domain.PP#5925d603]
);
Actual invocation has different arguments:
save(
"121",
[com.domain.PP#5b6e23fd,
com.domain.PP#1791fe40]
);
When I debugged the code, the code broke at the verify line below and threw the
above exception. Looks like the arguments inside the "testpPList" within the save
method is different. I dont know how it becomes different as I construct them in my
JUNit properly and then RestFul URL is invoked.
Requesting your valuable inputs. Thanks.
Code:
#Test
public void testSelected() throws Exception {
mockMvc.perform(put("/endpointURL")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(testObject)))
.andExpect(status().isOk());
verify(programServiceMock, times(1)).save(id, testpPList);
verifyNoMoreInteractions(programServiceMock);
}
Controller method:
#RequestMapping(value = "/endpointURL", method = RequestMethod.PUT)
public #ResponseBody void uPP(#PathVariable String id, #RequestBody List<PPView> pPViews) {
// Code to construct the list which is passed into the save method below
save(id, pPList);
}
Implementing the Object#equals(Object) can solve it by the equality comparison. Nonetheless, sometimes the object you are validating cannot be changed or its equals function can not be implemented. For such cases, it's recommended using org.mockito.Matchers#refEq(T value, String... excludeFields). So you may use something like:
verify(programServiceMock, times(1)).save(id, refEq(testpPList));
Just wrapping the argument with refEq solves the problem.
Make sure you implement the equals method in com.domain.PP.
[Edit]
The reasoning for this conclusion is that your failed test message states that it expects this list of PP
[com.domain.PP#6809cf9d, com.domain.PP#5925d603]
but it's getting this list of PP
[com.domain.PP#5b6e23fd, com.domain.PP#1791fe40]
The hex values after the # symbol for each PP object is their hash codes. Because they are different, then it shows that they belong to different objects. So the default implementation of equals will say they're not equal, which is what verify() uses.
It's good practice to also implement hashCode() whenever you implement equals(): According to the definition of hashCode, two objects that are equal MUST have equal hashCodes. This ensures that objects like HashMap can use hashCode inequality as a shortcut for object inequality (here, placing objects with different hashCodes in different buckets).

Throwing a NPE at the start of method for error checking

So im preparing for interviews and in one of Gayle Laakmans career Cup videos a guy is writing a simple method that takes in an array and does something with it. She mentions his lack of error checking so he adds in this line like so:
public int max(int[] array) {
if (array == null)
throw new NullPointerException();
//method body
}
Is it correct to manually throw a NPE exception like this, this exception will get thrown anyway in the method body as it will use the array reference at some point.
A possible advantage to this i can see is that it separates input invalidation from the method logic being invalid and somehow creating a null reference. Otherwise it is a little confusing and maybe IllegalArgumentException would work better?
There's nothing wrong with throwing NullPointerException as soon as you enter the method instead of waiting to detect it after some processing has already been done. If the method is going to fail, it might as well fail fast.
Joshua Bloch's Effective Java recommends throwing NullPointerException over IllegalArgumentException in this situation (Item 60: Favor the use of standard exceptions).
If a caller passes null in some parameter for which null values are prohibited, convention dictates that NullPointerException be thrown rather than IllegalArgumentException.
IllegalArgumentException should be thrown when an illegal non-null value is passed in.
Also have a look at java's own utility class java.util.Objects:
public static <T> T requireNonNull(T obj,
String message)
Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:
public Foo(Bar bar, Baz baz) {
this.bar = Objects.requireNonNull(bar, "bar must not be null");
this.baz = Objects.requireNonNull(baz, "baz must not be null");
}
Type Parameters:
T - the type of the reference
Parameters:
obj - the object reference to check for nullity
message - detail message to be used in the event that a NullPointerException is thrown
Returns:
obj if not null
Throws:
NullPointerException - if obj is null
from https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html
Conclusion
Whether or not you use this utility class is another question, but it definitely shows, that the team behind the Java language intended to use NullPointerException for these purposes.

Detect Exception thrown by a method in referenced DLL (.Net)

I have c#.net code which calls a method from another external/referenced .net assembly. This method I am calling throws an exception if a certain property from the object I am passing it is null. Here it is in a nutshell:
public void Add(string key, object obj)
{
..
//if the Foo property from obj is null then
throw new Exception("Foo property is null or empty")
..
}
In my client code which calls the DLL's Add method, I would like to be able to detect that this particular exception was raised, maybe distinguished by its "Foo property is null or empty" message. Currently, I get a NullReferenceException when it hits this method, so I catch this exception.
Question1:
Can I get the error message associated with the exception being thrown by the code I am calling (in the referenced assembly)??
Question2:
Is this considered bad practice or maybe just atypical?
Obviously, I can disassemble the third-party DLL to discover that my obj I'm passing in must have this "Foo" property set. So, my question here is somewhat for the sake of exercise (and because I'm a n00b).
Catching System.Exception and showing the exceptions Message property is all I needed. At first, I kept getting a NullReferenceException with "Object reference not set to instant of an object" message at the Add method, but I was expecting to get an Exception with the message "Foo property is null or empty" error. Some condition changed in my code and I now get what I expect.

TypeError: Error #1009 Actionscript 3

I am extremely frustrated. I'm following a tutorial and mimicing it on my own. I have been able to sort out most of the errors so far but this one has me stumped. I have tried replacing all of the class files with the tutorial specimen ones but i still get the error.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at com.senocular.utils::KeyObject/construct()
at com.senocular.utils::KeyObject()
at com.asgamer.basics1::Ship()
at com.asgamer.basics1::Engine()
Now, not really understanding the error properly I paste dumped the files online for you to look at.
Ship class: textbin.com/78z35
Engine class: textbin.com/32b24
KeyObject class: textbin.com/p2725
As the error still occured when using the specimen class files I really have no idea where to begin. I will gladly try out any suggestions.
Tip: If you allow debugging, the exception will tell you the exact line in the source code where the Error is being thrown. Assuming you're using the Flash IDE, go to publish settings and in the Flash tab check "Permit debugging". This will makes thing much easier for you.
Anyway, you have an error message. If you read it carefully, you can narrow down where the problem is. I don't know if you are a programmer or you have any interest in being one; if you're not, this answer will hopefully solve this particular problem. Anyway, if you don't mind the rambling, let me tell you that if you're interested in becoming a better programmer, paying attention to errors and learning how to debug / troubleshoot problems is one of the most important abilities you need to develop (if not the most important one); so maybe this will give you a few hints you can use to solve other problems as well.
The message says:
Cannot access a property or method of
a null object reference.
This means, at some point, you did something like this:
someobject.someMethod();
or
someobject.someProperty = "foo";
And someobject happened to be null. You can't call methods or access properties of null.
Ok, so now you know, somewhere, a variable had null as its value. Notice that the fact that you define a variable of property doesn't mean it actually holds an object.
This just says that a variable called mySprite can hold an object of the type Sprite:
var mySprite:Sprite;
But until at some point you create a Sprite and assign it to mySprite, the value held by mySprite will be null. If you do:
mySprite.x = 0;
Before initializing mySprite (i.e. before assigning a Sprite to it), you will have this same Null Reference error.
This error message also offers some helpul context, which you can use to your advantage (in them old days... errors in Flash were silent; when things didn't work, you had to manually trace down the problem).
Ok, let's break this error message down:
at com.senocular.utils::KeyObject/construct()
at com.senocular.utils::KeyObject()
at com.asgamer.basics1::Ship()
at com.asgamer.basics1::Engine()
What you have above is called a stack trace. It basically tells you where the code blew up, and also gives you some context: how did you get there.
The first line tells where the error actually occurred. That is, the construct method in the KeyObject object. That method was called from the KeyObject constructor, which was in turn called from the Ship constructor, which was in turn called from the Engine constructor.
Now, let's analyze how you got there, following the stack trace, bottom-up:
Code in Engine constructor:
ourShip = new Ship(stage);
This creates a new Ship object. It passes a reference to the stage to the Ship constructor method.
Code in Ship constructor:
this.stageRef = stageRef;
key = new KeyObject(stageRef);
It grabs the ref passed in the previous step. It stores it and creates a new KeyObject object. The KeyObject constructor is passed a reference to the stage (which is the same ref that was passed from Engine to Ship).
Code in KeyObject constructor:
KeyObject.stage = stage;
keysDown = new Object();
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
Now we got to the point where the error message told you the problem was. So, somewhere, you are using a variable that holds null and trying to access one of its methods or properties.
This KeyObject stores the reference to stage it was passed in a static variable and creates a new Object object. So far, no problems. KeyObject cannot be null (it's a reference to a Class). The second line itself cannot have this null problem either. So, if this is all the code in that method, the problem has to be either in the third or the fourth line. Both access the stage reference you passed and try to call a method (addEventListener) on it. So if one fails, the other will fail as well. Then, the third line: that's where the problem has to be.
So, at that point stage is null. As said previously, you can't call a method on null, and that's what the error is telling you.
Now, if you get back to the first method call, you can see this is the origin of the problem:
ourShip = new Ship(stage);
You can be pretty sure that, at this point, stage was null. Add that to the fact that Engine extends MovieClip (which is in turn a DisplayObject), and to the fact that any DisplayObject has a reference to the stage object only while it's added to the display list. The conclusion: an instance of Engine was not attached to the display list when its constructor was ran.
A way to fix this (there might be others) could be moving the code in the Engine constructor to a separate function that will be executed only if / when the Engine object has a valid reference to the stage object.
public function Engine() : void {
if(stage) {
initialize();
} else {
addEventListener(Event.ADDED_TO_STAGE,initialize);
}
}
private function initialize(e:Event = null):void {
removeEventListener(Event.ADDED_TO_STAGE,initialize);
// here goes the code that's currently in Engine constructor
}
Hope this helps.
I have a feeling your stage property is null.
You have have to test this yourself with a trace of the stage object.
In the first line in the constructor of you Engine class, add:
trace(stage);
Add that just above this line:
ourShip = new Ship(stage);
If it traces "null" then that is your problem.