Cannot handle FaultException by reflection invoking - targetinvocationexception

I am preparing a client for WCF service.
I provoked an fault exception in some method on a service site. I mean:
throw new FaultException<sth>(new sth())
When I catch this exception in WPF appliction:
catch (FaultException<sth> ex)
{
// something
}
everything works very clearly.
My point is, that I made a reflection on the service interface.
var type = typeof (someServiceInterface);
type.GetMethods();
and I want to catch the FaultException, when I call the method service in this way
try
{
var singleMethod = //do sth to get method
var result = singleMethod.Invoke(proxy, parameters);
return result;
}
catch (FaultException<sth> ex)
{
//1
}
catch (Exception ex)
{
//2
}
But I catch an Exception in second catch, not in the first. The type of this Exception is "System.Reflection.TargetInvocationException". I am confused and I wonder what cause such kind of problem.

Related

Handling CompressorException in Java8 Streams

I have a static method for reading .bz2 files, it throws checked IOException and org.apache.commons.compress.compressors.CompressorException. The function signature is:
private static MyClass readFile(String fileName) throws IOException, CompressorException{
//…
}
Trying to use this method outright with Java8 streams gets compile time errors in Intellij;
unhandled exceptions: java.io.IOException, org.apache.commons.compress.compressors.CompressorException
So following advice from here, among others, I’ve tried the following but am stuck on how to handle the CompressorException object. Following it’s ctor I’ve tried as below but Intellij still complains the CompressorException is unhandled:
files.stream().forEach(i -> {
try{
readFile(i);
} catch (IOException e){
throw new RuntimeException(e);
} catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
});
Thanks
As #JB Nizet mentioned in the comment, you cannot throw any Exception from the lambda function inside foreach function.
You need to replace your current implementation:
catch (Throwable ex){
throw new CompressorException("compressorException", ex);//error!!!
}
to either the following or not throw the RuntimeException at all.
catch (Throwable ex){
throw new RuntimeException("compressorException", ex);
}
The reason for the above behaviour is that the Stream.foreach() method has the following signature and doesn't throw any exception as part of the signature.
void forEachOrdered(Consumer<? super T> action)

Exception Handling in java to show user the catch error message from the nested method calls

I have doubt in Exception handling in java,when the exception is thrown in the called method, how to show the catch error in the calling method
Yes, it is possible to catch exception inside called method, and then re-throw same exception back to caller method.
public String readFirstLineFromFile(String path) throws IOException {
try {
BufferedReader br = new BufferedReader( new FileReader (path));
StringBuilder lines = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
System.out.println("REading file..." + line);
lines.append(line);
}
return lines.toString();
} catch(IOException ex) {
System.out.println("Exception in called method.." + ex);
throw ex;
}
}
Note: It is not possible if you are using try with resources, and exception occurred inside resources itself like opening of file, or file not found. In that case exception will be directly thrown back to caller.

ServiceStack catch (WebServiceException ex) - has wrong ErrorCode

In my ServiceStack service, I throw an exception that has an inner exception. When I caught a WebServiceRequest on the client side, the ErrorCode was the inner exception type name.
This is bad for me because it doesn't allow me to respond to the specific exception type that was thrown on the server.
I'm failing to see why ServiceStack was designed this way. It's pretty typical to catch lower level exceptions and wrap them with more informative and sometimes end-user friendly exceptions.
How can I change the default behavior so it uses the surface level exception and not the inner-most?
After looking at the first example at https://github.com/ServiceStack/ServiceStack/wiki/Error-Handling, I decided to check out at DtoUtils.HandleException, which looks like this:
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
if (ex.InnerException != null && !(ex is IHttpError))
ex = ex.InnerException;
var responseStatus = ex.ToResponseStatus();
if (EndpointHost.DebugMode)
{
// View stack trace in tests and on the client
responseStatus.StackTrace = GetRequestErrorBody(request) + ex;
}
Log.Error("ServiceBase<TRequest>::Service Exception", ex);
if (iocResolver != null)
LogErrorInRedisIfExists(iocResolver.TryResolve<IRedisClientsManager>(), request.GetType().Name, responseStatus);
var errorResponse = CreateErrorResponse(request, ex, responseStatus);
return errorResponse;
}
The very first instruction replaces the exception with it's inner exception. I'm not sure what the the thinking was with that. It seems counter intuitive to me and so I just re-implemented the method in my AppHost class, removing that first if statement block:
public override void Configure(Container container)
{
ServiceExceptionHandler += (request, exception) => HandleException(this, request, exception);
}
/// <remarks>
/// Verbatim implementation of DtoUtils.HandleException, without the innerexception replacement.
/// </remarks>
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
var responseStatus = ex.ToResponseStatus();
if (EndpointHost.DebugMode)
{
// View stack trace in tests and on the client
responseStatus.StackTrace = DtoUtils.GetRequestErrorBody(request) + ex;
}
var log = LogManager.GetLogger(typeof(DtoUtils));
log.Error("ServiceBase<TRequest>::Service Exception", ex);
if (iocResolver != null)
DtoUtils.LogErrorInRedisIfExists(iocResolver.TryResolve<IRedisClientsManager>(), request.GetType().Name, responseStatus);
var errorResponse = DtoUtils.CreateErrorResponse(request, ex, responseStatus);
return errorResponse;
}
This is obviously not ideal, since I had to copy a bunch of code that is totally unrelated to the problem that I had with the original implementation. It makes me feel like I have to maintain this method whenever I update ServiceStack. I would love to here of a better way to accomplish this.
Anyway, I have the exception handling that I like in my client code:
catch (WebServiceException ex)
{
if (ex.ErrorCode == typeof (SomeKindOfException).Name)
{
// do something useful here
}
else throw;
}
It doesn't seem like you'll have to maintain a bunch of code. You're writing one method to implement your own error handling. You could try calling DtoUtils.HandleException(this, request, exception) in your own method and modify the HttpError object returned. Not sure you have access to change all properties/values you're looking for.
public static object HandleException(IResolver iocResolver, object request, Exception ex)
{
HttpError err = (HttpError)DtoUtils.HandleException(this, request, ex);
err.Reponse = ex.InnerException;
}

How to catch the play.api.libs.openid.Errors$AUTH_CANCEL$ exception?

Using Play Framework 2.1 with OpenID, if I cancel my authentication from the OpenID Provider, I get this exception :
[RuntimeException: play.api.libs.openid.Errors$AUTH_CANCEL$]
Here's my code :
Promise<UserInfo> userInfoPromise = OpenID.verifiedId();
UserInfo userInfo = userInfoPromise.get(); // Exception thrown here
But since it's a Runtime exception, I can't catch it with a try/catch so I'm stuck on how to avoid exception and returns something nicer than a server error to the client.
How can I do that?
A Promise is success biased, for all its operations, it assumes it actually contains a value and not an error.
You get the exception because you try to call get on a promise which contains an untransformed error.
What you want is to determine if the Promise is a success or an error, you can do that with pattern matching for instance.
try this code:
AsyncResult(
OpenID.verifiedId.extend1( _ match {
case Redeemed(info) => Ok(info.attributes.get("email").getOrElse("no email in valid response"))
case Thrown(throwable) => {
Logger.error("openid callback error",throwable)
Unauthorized
}
}
)
)
You may want to read more on future and promises, I recommend this excellent article :
http://danielwestheide.com/blog/2013/01/09/the-neophytes-guide-to-scala-part-8-welcome-to-the-future.html
edit :
checking the documentation (http://www.playframework.com/documentation/2.1.0/JavaOpenID) in java it seems you are supposed to catch and handle exceptions yourself.
In any case, you should catch exceptions and if one is thrown redirect
back the user to the login page with relevant information.
something like this should work :
public class Application extends Controller {
public static Result index() {
return ok("welcome");
}
public static Result auth() {
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("email", "http://schema.openid.net/contact/email");
final Promise<String> stringPromise = OpenID.redirectURL("https://www.google.com/accounts/o8/id", "http://localhost:9000/auth/callback",attributes);
return redirect(stringPromise.get());
}
public static Result callback() {
try{
Promise<UserInfo> userInfoPromise = OpenID.verifiedId();
final UserInfo userInfo = userInfoPromise.get();
System.out.println("id:"+userInfo.id);
System.out.println("email:"+userInfo.attributes.get("email"));
return ok(userInfo.attributes.toString());
} catch (Throwable e) {
System.out.println(e.getMessage());
e.printStackTrace();
return unauthorized();
}
}
}

In languages with try-catch-finally, is it somehow possible to perform an action for all exception-handlers?

Is there any language that supports something like the below construct, or is there a good way to achieve this using the ubiquitous try-catch-finally?
try
{
} catch(Exception1 e)
{ .... }
catch(Exception2 e)
{ .... }
catch-finally
{
//Perform action, such as logging
}
finally
{
//This always occurs but I only want to log when an exception occurs.
}
I understand this depends on the particular language, but is there some such support in Java, C#, C++, PHP etc?
Put a "global" try/catch in your main program or high-level method. This catches all exceptions that are not caught elsewhere.
try
{
// Main method, or higher level method call
}
catch (Exception ex)
{
// Log exception here
}
Then, in your subordinate try/catch clauses, just handle your exceptions in the usual way, and then rethrow. The rethrown exception will bubble up to your main try/catch and be logged.
try
{
// Do your thing
}
catch(SomeException ex)
{
// Handle exception here
// rethrow exception to logging handler
throw;
}
I don't think so as the behaviour you describe can be easily modelled as:
boolean success = false;
try {
...
success = true;
} catch (Exception_1 e) {
...
}
...
} catch (Exception_N e) {
...
} finally {
if (success) {
// your "finally"
} else {
// your "catch-finally"
}
}
You can easily accomplish that in C#. A simple way would be to save the exception in your catch blocks, then in your finally block, log if the exception object is not null.
Exception ex;
try
{
}
catch (ExceptionType1 type1)
{
ex = type1;
}
catch (ExceptionType2 type2)
{
ex = type2;
}
finally
{
if (ex != null)
{
//Log
}
}
Visual Basic has a construct that can be used for this. This isn't really "finally" in the sense of [almost] never failing to execute, but it'll support the case when you only want to log the exceptions that you're handling, and you have access to the exception object within the shared code. You've also got the flexibility of having the shared code execute before or after the individual exception type code.
Try
...
Catch ex As Exception When TypeOf(ex) Is Type1 OrElse TypeOf(ex) Is Type2
...
If TypeOf(ex) Is Type1 Then
...
ElseIf TypeOf(ex) Is Type2 Then
...
End If
End Try
Something like this, as long as the language has throw with no parameters to rethrow a caught exception:
try
{
} catch(Everything) {
try {
throw;
} catch (Exception1 e) {
....
} catch (Exception2 e) {
....
} finally {
//Perform action, such as logging
}
} finally {
//This always occurs but I only want to log when an exception occurs.
}
That's if you want to log whenever an exception occurs - if you only want to log the ones you actually catch, then don't put the "Perform action" in a finally block, just put it after the end of the inner try-catch.