Are exceptions from RPCs the same as normal exceptions? - distributed-computing

Trying to understand more about RPCs to answer a homework question: Are exceptions handle the same way for the caller? Are the details of how exceptions are raised on the server any different? Are there any additional differences if you have to rethrow?
OR, can someone just explain what the main differences are between local and remote exceptions? And maybe give an idea of what things to look out for if I wanted to implement remote exceptions.

Here's a simple version of an RPC server / client library:
Server:
try
receive message
deserialize arguments
invoke appropriate method
serialize result
transmit result
catch any Exeption
serialize Exception
transmit Exception
Client (Library code, not the caller):
try
serialize arguments
make remote call
receive "something"
deserialize "something" (could be serialized exception or result)
catch Timeout,Network,Other exceptions not from server
handle whatever the library handles
if deserialized "something" is an exception
rethrow exception from server for caller to catch
else, good/expected results
return results
So, if you want exceptions to be caught by the caller, they possibly differ from regular exceptions in that they must be serialized and transmitted over the network to be re-thrown for the caller.
The caller need not do anything special if the Client library exists. If the client library doesn't exist, then the caller needs to also take the role of the client library. This means that the caller needs to distinguish between serialized results and serialized exceptions (at which point the programmer would probably implement an ad-hoc version of the client library code anyway just to avoid having ugly caller code).
Obviously you can't just use type signatures to distinguish between Exceptions and results (otherwise, what happens if the return type and the exception types for an RPC method were the same?). So there's a tiny bit of overhead in the serialization code for the server to label the different responses.

Related

Why is LinkageError Fatal in NonFatal.scala

I was looking at scala.util.control.NonFatal. I can't find the source, but I believe it is something like this.
They are declaring LinkageError as Fatal ...
Tomcat (at least last few years I used it) always returned 500 on catch Throwable, rather than crashing on certain kinds of errors. So do many other systems that make a best effort to always return something to the client.
So, my end question is when would you use NonFatal instead of making a best-effort attempt to provide some response?
As an example, now Futures in Twitter's Future library end up not resolving on NoSuchMethodError so my Future no longer resolves as failed with a Throwable but instead throw up the stack (differently from RuntimeException). In fact, in the open source Finagle stack, a NoSuchMethodError will cause the client socket connection to close on the client with no 500 http error back to customer. Customer then thinks 'hmm, network issue maybe ... why did my socket close'
So far, it has caused me nothing but issues and I admit to be a little frustrated, but need to be open to more use cases. For years, KISS and treating every Throwable in the catchall as non fatal has worked, but NonFatal is implying there are use-cases where we should do something different.
The source code of NonFatal is linked from the API docs.
Fatal errors are those from which your system or the JVM will most likely not recover correctly, so catching those errors is not a good idea.
The sub-classes of LinkageError are: ClassCircularityError, ClassFormatError, ExceptionInInitializerError, IncompatibleClassChangeError, NoClassDefFoundError, UnsatisfiedLinkError, VerifyError. These all occur when your class path is broken, there are invalid or binary incompatible class files. It's safe to assume that your entire system is broken if these happen at runtime.
To answer the question: You should "let it crash". Always use a NonFatal pattern match when you need a catch-all clause. It will also do you the favour and handle control-flow related exceptions correctly (e.g. NonLocalReturnControl).
Note that unlike the old source you link to, StackOverflowError is not non-fatal any longer, the decision was revised in Scala 2.11 as per SI-7999.

How to avoid handling RunTimeException in Jersey

The most popular desicion for handling exceptions in rest service and return the error message to client - as i understand - is to catch WebApplicationException or MappableContainerException. But they are extending RuntimeExceprion (I don't understand why). As I know we should avoid handling RuntimeExceptions.
I need to handle such exceptions as "The entity with such name already exsists". I'm sure it is not a runtime exception.
Any other ways? I'm researching now Wrappers. May be you could excplain me the best way to solve my problem?
The way that I handle this is to have my own exception hierarchy, and to build a separate ExceptionMapper which handles this hierarchy. That allows me to pass back whatever information I need to (in my case a JSON-formatted response) in a standardized way.
I would still have an ExceptionMapper for WebApplicationException, otherwise the end user might receive some nasty looking responses. And if you want to be extra-safe then you can also put one in for Exception that picks up anything else you might have missed (the exceptions go to the most specific exception mapper for them, so putting one in for Exception doesn't affect them).

HttpClient 4.1.x - Handling protocol error with body content

I've been doing some digging with an application system utilizing HttpClient 4.1.x to handle RESTful calls under Spring.
While I've got this working great under both directly dealing with the httpclient as well as using as the transport for the RestTemplate, I've found that I have a need for something that I'm not sure was covered in execution.
The "BasicResponseHandler" treats the content response as a string and returns it provided that the response from the server is less than 300. The RESTful system I'm working with provides an XML document as part of an error response (status code >= 400). This XML response contains some information that may be of use to the client developer.
What I'd like to see if anyone has any experience dealing with this via the ResponseHandler interface. Essentially, the BasicResponseHandler will toss a ClientProtocolException in the case that there is a status >= 300. The handling AbstractHttpClient implementation will trap that exception, consume the entity silently, then re-throw the IOException (ClientProtocolException) that was thrown.
Would it be advisable to create a sub-class of ClientProtocolException to contain the additional information?
In the case of the error status, unmarshal any existing document into its respective type (if available) and then throw it thus preserving the content of the response.
Or is there another mechanism that I'm missing to handle this case?
The purpose of the ResponseHandler interface is to enable the caller to digest HTTP responses without buffering message content in memory. An extra benefit of using this interface is not having to worry about resource deallocation which is taken care of automatically by HttpClient.
In your particular case you should consider building a higher level domain object from the low level HTTP response content instead of returning a simple, unrepresentative string.
So, instead of throwing an exception, consider returning back to the caller an object consisting of the request status (success, failure, partial response, etc), and a parsed XML document or an JAXB object representing a message content.

How to "throw" a %Status to %ETN?

Many of the Caché API methods return a %Status object which indicates if this is an error. The thing is, when it's an unknown error I don't know how to handle (like a network failure) what I really want to do is "throw" the error so my code stops what it's doing and the error gets caught by some higher level error handler (and/or the built-in %ETN error log).
I could use ztrap like:
s status = someObject.someMethod()
ztrap:$$$ISERR(status)
But that doesn't report much detail (unlike, say, .NET where I can throw an exception all the way to to the top of the stack) and I'm wondering if there are any better ways to do this.
Take a look at the Class Reference for %Exception.StatusException. You can create an exception from your status and throw it to whatever error trap is active at the time (so the flow of control would be the same as your ZTRAP example), like this
set sc = someobj.MethodReturningStatus()
if $$$ISERR(sc) {
set exception = ##class(%Exception.StatusException).CreateFromStatus(sc)
throw exception
}
However, in order to recover the exception information inside the error trap code that catches this exception, the error trap must have been established with try/catch. The older error handlers, $ztrap and $etrap, do not provide you with the exception object and you will only see that you have a <NOCATCH> error as the $ZERROR value. Even in that case, the flow of control will work as you want it to, but without try/catch, you would be no better off than you are with ZTRAP
These are two different error mechanisms and can't be combined in this way. ztrap and %ETN are for Cache level errors (the angle bracket errors like <UNDEFINED>). %Status objects are for application level errors (including errors that occurred through the use of the Cache Class Library) and you can choose how you want to handle them yourself. It's not really meaningful to handle a bad %Status through the Cache error mechanism because no Cache error has occurred.
Generally what most people do is something akin to:
d:$$$ISERR(status) $$$SomeMacroRelevantToMyAppThatWillHandleThisStatus(status)
It is possible to create your own domain with your own whole host of %Status codes with attendant %msg values for your application. Your app might have tried to connect to an FTP server and had a bad password, but that doesn't throw a <DISCONNECT> and there is no reason to investigate the stack, just an application level error that needs to be handled, possibly by asking the user to enter a new password.
It might seem odd that there are these two parallel error mechanisms, but they are describing two different types of errors. Think of one of them being "platform" level errors, and the other as "application level errors"
Edit: One thing I forgot, try DecomposeStatus^%apiOBJ(status) or ##class(%Status).LogicalToOdbc(status) to convert the status object to a human readable string. Also, if you're doing command line debugging or just want to print the readable form to the principal device, you can use $system.OBJ.DisplayError(status).

error handling vs exception handling in objective c

I am not able to understand the places where an error handling or where an exception handling should be used. I assume this, if it is an existing framework class there are delegate methods which will facilitate the programmer to send an error object reference and handle the error after that. Exception handling is for cases where an operation of a programmer using some framework classes throws an error and i cannot get an fix on the error object's reference.
Is this assumption valid ? or how should i understand them ?
You should use exceptions for errors that would never appear if the programmer would have checked the parameters to the method that throws the exception. E.g. divide by 0 or the well known "out of bounds"-exception you get from NSArrays.
NSErrors are for errors that the programmer could do nothing about. E.g. parsing a plist file. It would be a waste of resources if the program would check if the file is a valid plist before it tries to read its content. For the validity check the program must parse the whole file. And parsing a file to report that it is valid so you can parse it again would be a total waste. So the method returns a NSError (or just nil, which tells you that something went wrong) if the file can't be parsed.
The parsing for validity is the "programmer should have checked the parameters" part. It's not applicable for this type of errors, so you don't throw a exception.
In theory you could replace the out of bounds exception with a return nil. But this would lead to very bad programming.
Apple says:
Important: In many environments, use of exceptions is fairly commonplace. For example, you might throw an exception to signal that a routine could not execute normally—such as when a file is missing or data could not be parsed correctly. Exceptions are resource-intensive in Objective-C. You should not use exceptions for general flow-control, or simply to signify errors. Instead you should use the return value of a method or function to indicate that an error has occurred, and provide information about the problem in an error object.
I think you are absolutely right with your assumption for Errors and for it framework provide a set of methods (UIWebView error handling ), But your assumption for Exception partially right because the exception only occurred if we do something wrong which is not allowed by the framework and can be fixed. (for example accessing a member from an array beyond its limit).
and will result in application crash.