I am unable to create an instance of SQLServerException because the ctors are all internal. Getting below error when using SQLException
org.mockito.exceptions.base.MockitoException: Checked exception is
invalid for this method!
Method signature (on SQLServerPreparedStatement):
public boolean execute() throws SQLServerException, SQLTimeoutException
and... public final class SQLServerException extends SQLException
Mock:
val fakeCmd : SQLServerPreparedStatement = mock()
...
whenever(fakeCmd.execute()).thenThrow(SQLException()) // this line fails
What am I doing wrong? Shouldn't I be able to throw the base/super exception?
Re Suggested Question:
The suggested question is very different from what I'm asking, the op in the other question is trying to throw SomeException which is not thrown by List.get nor in the inheritance tree
If you see "Method signature (on SQLServerPreparedStatement)" above, the method throws SQLServerException => public final class SQLServerException extends SQLException
But it doesn't like whenever(fakeCmd.execute()).thenThrow(SQLException())
Further, the accepted answer as pointed out is to throw RuntimeException because IndexOutOfBoundsException extends RuntimeException
In this case, so is SQLServerException extends SQLException
I commented about another question and there is a answer (not the accepted one) in the end that may be suitable in your case.
A workaround is to use a willAnswer() method.
For example the following works (and doesn't throw a MockitoException but actually throws a checked Exception as required here) using BDDMockito:
given(someObj.someMethod(stringArg1)).willAnswer(invocation -> {
throw new Exception("abc msg");
});
The equivalent for plain Mockito would to use the doAnswer method
Here is the direct link to that answer: https://stackoverflow.com/a/48261005/13210306
Related
(Trying to keep this simple.)
I have a (partial) ByteBuddy recipe like this:
builder
.method(someMatcher())
.intercept(MethodDelegation.to(this.interceptor));
I have an "interceptor" class defined like this:
private static final class Interceptor {
private Interceptor() {
super();
}
#RuntimeType
private final Object doSomething(#This final Proxy<?> proxy,
#SuperCall final Callable<?> callable,
#Origin final String methodSignature) throws Exception {
final Object proxiedInstance = proxy.getProxiedInstance();
// TODO: logic
return callable.call(); // for now
}
}
(The interceptor method needs to be non-static for various reasons not important here.)
When I create an instance of this ByteBuddy-defined class and call a simple public void blork() method on it, I get:
Cannot resolve ambiguous delegation of public void com.foo.TestExplorations$Frob.blork() to net.bytebuddy.implementation.bind.MethodDelegationBinder$MethodBinding$Builder$Build#3d101b05 or net.bytebuddy.implementation.bind.MethodDelegationBinder$MethodBinding$Builder$Build#1a9efd25
How can there be ambiguity when there is only one interceptor? What have I done wrong?
Byte Buddy just adds a method call to the instrumented class which needs to be able to see the target class. If it is private, it is ignored and Byte Buddy searches further up the hierarchy where it finally consideres the methods of Object which are all equally unsuited but therefore an ambiguity exception is thrown instead of an exception that no method could be bound.
Consider the following handler:
public class CreateProjectHandler extends AbstractHandler {
#Override
public Object execute(ExecutionEvent event) throws ExecutionException {
// it does not matter what kind of exception this is:
throw new IllegalArgumentException("This is a test!");
}
}
From a customer and developer perspective it's pretty clear what should happen when this handler is executed: an error message of some kind should pop up.
What happens is: Nothing.
More accurate: the exception is logged into the error log (and console, if started from Eclipse). But the user sees nothing, in fact he doesn't even know there was an error.
I could fix this by catching Exception for each and every handler, but besides being ugly and cumbersome it contradicts each style guide ever.
Is there a better way to handle the exceptions swallowed by handlers?
For Eclipse 4 (e4 or 3.x compatbility mode) add a class implementing IEventLoopAdvisor to the application context. The eventLoopException method will be called for the unhandled exceptions.
A suitable place to set this up for e4 is the #PostContextCreate of the RCP life cycle class:
#PostContextCreate
public void postContextCreate(IEclipseContext context)
{
// Event loop advisor for error handling
context.set(IEventLoopAdvisor.class, new EventLoopAdvisor());
You must also implement eventLoopIdle, it is very important that this calls display.sleep(). A standard method would be:
#Override
public void eventLoopIdle(final Display display)
{
display.sleep();
}
For 3.x compatibility mode there is a default event loop advisor installed after the post context create which delegates to the workbench WorkbenchAdvisor. If you are using your own advisor in the RCP you can override the eventLoopException method of the advisor.
I found another way that works for my E3 compatibility application: overridding WorkbenchAdvisor#eventLoopException(Throwable):
public class ApplicationWorkbenchAdvisor extends WorkbenchAdvisor {
#Override
public void eventLoopException(Throwable exception) {
// do magic here
}
// [snipped other methods]
}
Ok, so I have asked another question on the same topic here and while I did not get a direct answer there I've pulled together some code that I got working to do what I wanted. Question is, does this way break some OOP principle?
What I wanted
Use proper OOP to declare fault types on a service
Have one catch block in the client side that can handle multiple types of exceptions thrown from the service
Have one HandleException method per fault class that has its own implementation
On the client side have just one exception block understand what exception was thrown and call the respective HandleException method from the corresponding fault class
How I got it working
Declared a fault contract on server for each exception type that inherits from a base exception type
[DataContract]
public class BusinessRuleViolationFault : BaseFault
{
public BusinessRuleViolationFault(string message)
: base(message)
{
}
}
[DataContract]
public class SomeOtherViolationFault : BaseFault
{
public SomeOtherViolationFault(string message)
: base(message)
{
}
}
[DataContract]
public abstract class BaseFault
{
public BaseFault(string message)
{
Message = message;
}
}
On the client side I created partial classes of the same fault types as above and implemented the handle exception method in it. I had to do this on the client side since if I created this method on the service side it would not get serialized and be available via the proxy.
public partial class BusinessRuleViolationFault : BaseFault
{
public override void HandleException()
{
MessageBox.Show("BusinessRuleViolationFault handled");
}
}
public partial class SomeOtherViolationFault : BaseFault
{
public override void HandleException()
{
MessageBox.Show("SomeOtherViolationFault handled");
}
}
public abstract partial class BaseFault
{
public abstract void HandleException();
}
Then created an extension method on the faultexception class as per Christians code which I have marked as accepted answer in my previous post. This basically used reflection to get me the name of the fault exception class that was thrown.
Then in my client catch block I used that name to create an instance of the locally created partial class which has the handle exception method.
What I am curious to know is, have I broken some OOP principle here?
Is this OOP at all?
I dont want multiple if else statement in this one catch block or have multiple catch blocks. What is your opinion on the tradeoff of using one catch block to gain performance and lose it with reflection by trying to figure out what class method to call?
Thanks for your time and patience ...
I don't understand exactly why reflection is needed here (as described in the previous posted question). I simply do this in my code and it works fine:
try
{
proxy.CallServiceMethod(message);
}
catch (Exception e)
{
if (e is FaultException<BaseFault>)
{
BaseFault exceptionToHandle =
(e as FaultException<BaseFault>).Detail as BaseFault;
exceptionToHandle.HandleException();
}
}
Aside from the unnecessary reflection, I don't see anything wrong with the way you have implemented this (from an OOP point of view at least).
I have an interface with a method marked with the obsolete attribute. The attributes error parameter is set to true to throw an exception when used. The problem is this causes the stub to not generate for the whole class. When I alter the value to false the stub generates as expected.
I’m looking for a way to generate the stub while retaining the error parameter as true.
public interface ICar
{
void Start();
[Obsolete("this is obsolete Stop, stop using it", true)]
void Stop();
}
I’ve tried different permutations of.
<Moles xmlns="http://schemas.microsoft.com/moles/2010/">
<Assembly Name="My.Car.Services"/>
<StubGeneration>
<TypeFilter TypeName="ICar" SkipObsolete="true" />
</StubGeneration>
</Moles>
This is by design. When a method is marked at Obsolete(..., true), C# will not allow to instantiate an class implementing that interface.
I implemented a class that implements IErrorHandler interface to log WCF errors. One of the things that I'd like to do is log who the identity of the user than connected to my service when an exception occurred. All my logging occurs in HandleError() method of IErrorHandler interface, but since HandleError() may not have current operation context, I can't get the SecurityContext.PrimaryIdentity. I've come up with the following code to capture things that may not be available in HandleError method, but I'm not sure this will work in all cases.
public class MyErrorHandler : IErrorHandler
{
private IIdentity identity;
public bool HandleError(Exception error)
{
// Do something with identity
return false;
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
this.identity = Operation.Current.SecurityContext.PrimaryIdentity;
}
}
The code above seems to be working, but are there any gotchas?
Thanks!
For some reason, I thought that the class was created every time there was an exception. In any case, I was able to solve my issue by using Dictionary property of Exception object to store custom data that I wanted to log with my exception.