Still undecided how to handle errors in Swift 2 - error-handling

I have a maybe silly question. I coming from programming languages with exception handling, e.g. C++ and C#. At the time of Swift 1 I was confronted with the Cocoa Style with error objects (which somewhat reminded me at the ErrorObject in Microsoft COM).
After a time I began to use for my side project app an error handling pattern, in which I used a function parameter (closure) for error handling:
public typealias FailureBlock = (error:NSError!)->Void
JournalEntryStorage.instance.createJournalEntry(journalInfo, failure:
{
error in
NSLog("Watch App saveNewEntryInJournal: \(error.description)")
})
This solution seems nice at the time, because the function parameter forces me to code the error handling logic or I could simply make a call to a passed error handler function.
Now we have a solid error handling in place with Swift 2. Should I change my code completely to the new pattern? There is a lot of code.
How do you deal with your (legacy) code and the new error pattern?
By the way: I found the original Cocoa way with passing an error pointer and dealing with it so ugly in Swift 1. Maybe my method is more ugly but for me it seemed working.

I have decided for following solution and close the question:
a) I leave my old error handling pattern for all asynchronous function calls.
b) I am converting all synchronous functions to the new error handling scheme.
First impression. The code is much more readable.

Related

Is there an efficient way to avoid instantiating a class with syntax errors?

As you may know, it is pretty easy to have active code of a class containing syntax errors (someone activated the code ignoring syntax warnings or someone changed the signature of a method the class calls, for instance).
This means that also dynamic instantiation of such a class via
CREATE OBJECT my_object TYPE (class_name).
will fail with an apparently uncatchable SYNTAX_ERROR exception. The goal is to write code that does not terminate when this occurs.
Known solutions:
Wrap the CREATE OBJECT statement inside an RFC function module, call the module with destination NONE, then catch the (classic) exception SYSTEM_FAILURE from the RFC call. If the RFC succeeds, actually create the object (you can't pass the created object out of the RFC because RFC function modules can't pass references, and objects cannot be passed other than by reference as far as I know).
This solution is not only inelegant, but impacts performance rather harshly since an entirely new LUW is spawned by the RFC call. Additionally, you're not actually preventing the SYNTAX_ERROR dump, just letting it dump in a thread you don't care about. It will still, annoyingly, show up in ST22.
Before attempting to instantiate the class, call
cl_abap_typedescr=>describe_by_name( class_name )
and catch the class-based exception CX_SY_RTTI_SYNTAX_ERROR it throws when the code it attempts to describe has syntax errors.
This performs much better than the RFC variant, but still seems to add unnecessary overhead - usually, I don't want the type information that describe_by_name returns, I'm solely calling it to get a catchable exception, and when it succeeds, its result is thrown away.
Is there a way to prevent the SYNTAX_ERROR dump without adding such overhead?
Most efficient way we could come up with:
METHODS has_correct_syntax
IMPORTING
class_name TYPE seoclsname
RETURNING
VALUE(result) TYPE abap_bool.
METHOD has_correct_syntax.
DATA(include_name) = cl_oo_classname_service=>get_cs_name( class_name ).
READ REPORT include_name INTO DATA(source_code).
SYNTAX-CHECK FOR source_code MESSAGE DATA(message) LINE DATA(line) WORD DATA(word).
result = xsdbool( sy-subrc = 0 ).
ENDMETHOD.
Still a lot of overhead for loading the program and syntax-checking it. However, at least none additional for compiling descriptors you are not interested in.
We investigated when we produced a dependency manager that wires classes together upon startup and should exclude syntactically wrong candidates.
CS includes don't always exist, so get_cs_name might come back empty. Seems to depend on the NetWeaver version and the editor the developer used.
If you are certain that the syntax errors are caused by the classes’ own code, you might want to consider buffering the results of the syntax checks and only revalidate when the class changed after it was last checked. This does not work if you expect syntax errors to be caused by something outside those classes.

Debug Async MVC Action Controller with nested Async Methods

I am calling a ASYNC method in an MVC4 application. This method has to call a dozen or so other methods, which are nested. My issue is that if any of these nested methods break, it passes the error to the parent method. Since they are all nested, it just keeps passing up the chain returning to the HTTP context the generic error message.
Since I have so many nested methods, I have no clue how to find more information on the error. Even a simple line that broke would be extremely helpful.
Right now I am resorting to breaking every line to see which ran last before it stop responding. This Method alone, with it's nested methods, are over 2000 lines of code. As you can tell, this is a very un-effective way at debugging.
Any help at a better way of finding out where a ASYNC method actually broke, when in nested methods, would be extremely helpful. I really want to avoid doing a Try/Catch on every method I have.
-- Edit --
This has been answered. I put my solution below and will mark it as answered in two days, per StackOverflow restrictions.
Apparently if I put a Try/Catch on the first call inside my Action Method it at least gives me the line in the stack trace. Once noting this, I added ELMAH and inspected my error log when throwing a generic exception. It appears that the line gets passed back to ELMAH also.
While this is not nearly as nice as normal exception breaking in visual studio, it allows me to easily put a breakpoint on that exact line to see what is happening.
Unfortunately, asynchronous "stack traces" do not work very well out of the box.
You can do your own tracing using a technique I describe in this blog post. Or you could try installing my async diagnostics package which adds the asynchronous "stack trace" to the exception's Data property (note: not logged by default in ELMAH). However, this package is not yet production-ready, so I recommend uninstalling before deploying.

Duplication of interface error in xcode

I am not even sure how to start.
I am developing an iPhone application with the latest Xcode and sdk using core plot and the core async socket library. Everything was fine until a few hours ago, when Xcode dumped a ton of "interface duplication" errors for no apparent reason.
The two files that are emitting errors are the AsyncSocket.h and an API client that I wrote in order to get data out of the target server.
The errors are the following:
Nested Redefinition error on all enums in AsyncSocket.h and my API client.
Redeclaration of enum on all enumerations in AsyncSocket.h and my API client.
Duplicate interface declaration on the AsyncSocket.h and the API client's interface file.
The error occurred between two builds of the application. NOTHING was changed during that time which is why I can't even begin to think what is causing this.
The API client is a really simple thing, it just uses the async socket to send queries to the server and then return the parsed results in arrays. Nothing complicated, as I am not that into objective c yet.
I wish I could give some more useful information but that is all I have.
i believe your problem results from a simple mistake. In the header file you begin with:
#interface ClassName : SuperclassName
while in the .m file you do:
#interface ClassName ()
When you forget the brackets, the compiler complains.
I hope this helps. Best wishes with your app.
I had this problem and the response above put me on the right track.
I created a new enum record in a .h file I use for all my Constants.
But I forgot to add the semi-colon on the end. This simple little syntax error resulted in some weird and confusing errors appearing on files other than the one which contained the error.
No doubt you've resolved this by now but it might fix someone else's issues in the future.
I also experienced the "Duplicate interface definition" error message and traced it to my having put an "#include xxx.h" in a header (.h) file instead of in the .m file where I intended to put it.

How are try/catch blocks implemented?

If an exception occurs in a try block, how is execution transferred to the catch block? This is not a C#/Java/C++ question, I'm just wondering how it works internally.
this is not a c#/java/c++ question. How it works internally,how the line knows to go catch statement.
How this works internally makes this pretty much a c#/java/C++ question (because it will be implemented differently).
In Java, a try block installs itself into a special table (in the class file). When the JVM throws an exception, it looks at that table to see where the next catch or finally block to go to is.
When an exception occurs a special instruction is executed (usually called interrupt). This leads to executing a generic error handler that deduces which is the latest installed suitable exception handler. That handler is then executed.
There is a difference how exceptions are technically handled between natively compiled languages such as C++ and languages using byte-code being executed on a virtual machine such as Java or C#.
C++ compilers usually generate code that protocols the information needed for exception handling at runtime. A dedicated data structure is used to remember entrance/exit of try blocks and the associated exception handler. When an exception occurs, an interrupt is generated and control is passed to the OS which in turn inspects the call stack and determines which exception handler to call.
Further details are pretty well explained in the following article by Vishal Kochhar:
How a C++ compiler implements exception handling
In Java or .NET there is no need for the overhead of maintaining exception handling information as the runtime will be able to introspect the byte code to find the relevant exception handler. As a consequence, only exceptions that are actually thrown are causing an overhead.
It is basically parsing fundamentals of the language.
You can get all info at Here
it should work in all langues somewhat like this:
if (error_occured xy while doing things in try){
call_catch_part(error xy)
}
you could do the same in C even though there is no exception handling per se.
There you would use setjmp/longjmp unfortunately you then do not get the stack unwinding and have to handle all the nitty-gritty yourself.

Which Error Handling Model Is More Robust?

I'm kind of torn between these two error-handling models:
Create a boolean Error and a string ErrorMessage property for your object. Catch all exceptions internally in the object's methods and pass the messages along using conditional logic from the caller, ie:
Dim o As New MyObject
o.SomeMethod()
If Not o.Error Then
'Do stuff'
Else
Dim msg As String = o.ErrorMessage
'do something with message'
End If
Throw exceptions in your object and handle them on the outside with Try Catch logic:
Dim o As New MyObject
Try
o.SomeMethod()
'Do stuff'
Catch ex As Exception
Dim msg As String = ex.ErrorMessage
'do something with message'
End Try
To me, it seems like the same amount of code either way, except that you have property code for the Error and ErrorMessage properties. However, you also can tell when an error occurs without having to check for exceptions. Which pattern should I go with?
I have decided to go with throwing exceptions instead of using error/return codes. I just recently looked really hard into this.
The #1 reason to throw exceptions is there is a possibility you can forget to check the error code. If you don't check it, then you will continue working while the error exists. With exceptions though, if you forget to handle them, then the exception will raise to the top and stop all processing. It is better for this to happen than to continue after unknown errors have occurred.
For more info check out the Exception chapter in Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries, Second Edition by Addison-Wesley.
Joel Spolsky actually prefers error/return codes over exceptions but a lot of people disagree with him. Joel's post in favor of return codes can be found here. Check out this blog post and all of the comments with some good discussion regarding this subject.
Prefer #2. For details, see this excerpt on Exception Throwing from the development of Microsoft's excellent Framework Design Guidelines, as Dennis mentioned. Note especially the section on Exceptions and Performance.
Short version:
Do not return error codes.
Do report execution failures by throwing exceptions.
Do not use exceptions for normal flow of control.
I highly recommend reading the book for a full discussion, complete with commentary from a number of the Microsoft luminaries.
Exceptions should be used when something exceptional has happened.
e.g. you are passed a null (nothing) object when you expect one.
Uncle Bob recommends Exceptions over Error codes in his book Clean code.
He says
The problem with these [error codes] approaches is that they clutter the caller. The caller must check for errors immediately after the call. Unfortunately it's easy to forget. For this reason it is better to throw an exception when you encounter an error. The calling code is cleaner. Its logic is not obscured by error handling.
The biggest issue I have with the first one is that it's passive, easily overlooked and not very standardized. How will a programmer know to check that property? Or which properties / methods can possible set an error? Or which property / method access caused the error to be set?
For example. In your first sample code if o.Error is True, it's unclear whether the initialization of the object or the call to SomeMethod caused the flag to be set.
The exception model is an unignorable way of telling your users that an error occurred. It cannot be avoided without explicit code to handle the situation.
They are both accepted forms of error handling, however the preferred choice for .NET languages is to use exceptions.
There are a few problems with using return codes (either numeric or boolean), the two biggest being:
Easily overlooked/ignored by programmers.
Can't be used in all situations. What happens if your constructor fails? It's not possible for you to return a value explicitly from a constructor.
For these reasons alone, you should use exceptions. Exceptions provide a clean, standardized way to indicate and any failure no matter where it arises.
You will also end up with less code overall as you should only catch exceptions when and where you can safely and appropriately handle that exception.
I recommend using both.
Why?
"Use the right tool for the job"
The "problem" with return codes is that people often forget to handle them. However, exceptions don't solve this problem! People still don't handle exceptions (they don't realise a certain exception needs to be handled, they assume somebody up the stack will handle it, or they use a catch() and squash all errors).
While an unhandled return code might mean the code is in an unstable state, an unhandled exception often guarantees that the program will crash. Is this better?
While a return code is easily identifiable when writing code, it is often impossible (or just tediously time-consuming) to determine what exceptions might be thrown by a method you are calling. This typically results in a lot of very poor exception handling.
Exceptions are supposed to be used for "errors". Therein lies the difficulty. If a file is not found when you try to open it, is that an "error", or an "expected situation"? Only the caller knows. Using exceptions everywhere essentially elevates every piece of status information into an error.
Ultimately, error handling is something a programmer has to work at. This problem exists in both return codes and exceptions.
Thus, I use return codes for passing status information (including "warnings"), and exceptions for "serious errors". (and yes, sometimes it's hard to judge which category something falls under)
Example case from .net:
Int32.Parse throws exceptions (even though none of its exceptions are errors - it is up to the caller to verify the results and decide for themselves if the result is valid). And it's simply a pain (and a performance hit) to have to enclose every call to it in a try/catch. And if you forget to use a try/catch, a simple blank text entry field can crash your program.
Thus, Int32.TryParse() was born. This does the same thing, but returns an error code instead of an exception, so that you can simply ignore errors (accepting a default value of 0 for any illegal inputs). In many real life situations this is much cleaner, faster, easier and safer to use than Int32.Parse().
"TryParse" uses a naming convention to make it clear to the caller that errors might occur, that should be correctly handled. Another approach (to force programmers to handle errors better) is to make the return code into an out or ref parameter, so that the caller is explicitly made aware of the need to handle returned errors.