What is the difference between Rejection and Exception in akka-http - akka-http

I don't get the difference between Rejection and Exception in akka-http, they look redundant to me since they are managed almost the same way.
Is is not possible to have a Rejection of type Exception so in our Directives we can catch Exception and trigger the appropriate Rejection instead.

The difference between Rejection and Exception is semantic.
Rejection allows you to do validation of request parameters. If some of the parameters do not match(incorrect for this directive) than directive can reject the request and some other directives can try to match request and handle than.
Exception means that you have unexpected behavior in your directive. Usually, it is after matching when directive processes request.
As I understand from your question you can have one of the situations below:
You have exception while matching directive it probably means that you can not do proper validation and the only way is call function and look for exception. If an exception is thrown it means that directive does not match and you create rejection.
You create rejection as a part of exception handling. It is one of the ways of handling exception. Another one is just returning response with 501 status code and Internal Server Error.
Both of this situations make sense but they do not mean that rejection and exception are similar things.

Related

Flask: difference between #app.errorhandler(500) and #app.errorhandler(exception)

From my understanding, #app.errorhandler(500) changes the default error for unhandled errors, while #app.errorhandler(exception) catches all errors (except ones already specified with a handler). Doesn't that mean that both of these things achieve the same thing essentially? is there really a difference
#app.errorhandler(500) would handle errors stemming from a page that returns a HTTP status code of 500. Whereas #app.errorhandler(exception) is more broad and can be used for global exception handling. For example if your code raises an OSError exception, this is where the exception shall be handled (unless the offending code is covered by its own try/catch block).
So it can be convenient for example to use #app.errorhandler(404) to customize your 404 Not found page and use #app.errorhandler(exception) all along for the more serious Python exceptions.

ctx.commandFailed vs throwing in PersistentEntity

In the Auction Example I have seen both ctx.commandFailed(...) and throw SomeException(...). Is there a good reason to throw instead of using the API and is there a difference between the two?
Persistent entity command handlers and after persist callbacks are wrapped in try/catch blocks, if an exception is caught, it will pass that exception to ctx.commandFailed(...) for you.
There is a subtle difference between the two to be aware of. If you throw an exception, processing of the command will of course stop immediately. If however you pass an exception to ctx.commandFailed(...), that will send the exception back to the invoker of the command, however it won't stop processing. You could in theory go on to return some directives to persist events - which would be an odd thing to do. In practice what you need to do is return ctx.done after invoking ctx.commandFailed(...).
In general it's probably simpler and safer to simply throw the exception.

when it is correct purpose of exceptions

I am studying OOP, and I did not understood the concept of exception.
What are the correct uses of exceptions?
Why use exceptions when you already know a possible exception?
For example, I have seen a code sample where the programmer needed to access a file, and had an exception in case the file does not exist. Something like "catch(fileDoesNotExist e)".
Why not use an if to verify before take the action? And use exception only for not known issues, for logging or error messages.
The idea behind the concept of exception was to decouple the error handling code from the "normal" behaviour flow control. That lets to manage/handle the exception further up the call stack.
Historically, with structured language, error handling code (file opening error,...) was mixed within the "business" application code. It was also painful to improve the code in order to manage new error codes.
What are the correct uses of exceptions?
If it is not normal that your file doesn't exist or cannot be opened => it is considered as an exceptional situation => exception => exception handler
Why use exceptions when you already know a possible exception?
To decouple the business application code from the error handling. That eases source code readibility and maintenance.
Exception:
Exception is that interrupt(break) the normal flow of the program.It's thrown at runtime.
Exception Handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL, Remote etc
In java there are mainly two types of exception that checked and unchecked.Other than Error is there
Hierarchy of Exception classes in Java
Why use exceptions when you already know a possible exception?
basically exception handling use to mainly,we assuming in that our particular code will occur some(NullPointerException,ArrayIndexOutOfBoundsException etc..)exception.If we not Handle that,program will break.Actually that Exception it may or may not will happen.But so we need to handle normal flow of the program it occurred or not.Otherwise after that particular code section not executing.

Mule global catch exception not being called

I'm using the global exception strategy at this link
Global Catch Exception Strategy is not used
I use a ref to this in each of my flow footers and have also used defaultExceptionStrategy-ref="catchExceptionStrategy" as shown in the link. But this exception
org.mule.exception.DefaultSystemExceptionStrategy: Caught exception in Exception Strategy: null
java.util.ConcurrentModificationException
...
is not being caught by my global exception. My assumption was that this is a message exception and the flow refs would therefore direct it to the global catch. Also that the defaultExceptionStrategy-ref configuration would direct any other exceptions to the global catch.
The log you are showing proves that the exception strategy is actually called but there has been a concurrent modification exception on it. In order to help you further we would need to understand better what is in you message when the exception happens and the actual xml of your exception strategy.

To fault or not to fault

I'm having a discussion with a colleague about when to throw faults and when not to throw faults in a WCF service.
One opinion is, that we only throw faults when the service operation could not do its work due to some error; and something may be in an invalid state because of it. So, some examples:
ValidateMember(string name, string password, string country)
-> would throw a fault if the mandatory parameters are not passed, because the validation itself could not be executed;
-> would throw fault if some internal error occured, like database was down
-> would return a status contract in all other cases, that specifies the result of the validation (MemberValidated, WrongPassword, MemberNotKnown,...)
GetMember(int memberId)
-> would only throw fault if something is down, in all other cases it would return the member or null if not found
The other opinion is that we should also throw faults when GetMember does not find the member, or in the case of ValidateMember the password is wrong.
What do you think?
My take on this...
There are three causes of failure:
The service code threw an exception, e.g. database error, logic error in your code. This is your fault.
The client code failed to use your service properly according to your documentation, e.g. it didn't set a required flag value, it failed to pass in an ID. This is the client software developer's fault.
The end user typed in something silly on screen, e.g. missing date of birth, negative salary. This is the end user's fault.
It's up to you how you choose to map actual fault contracts to each cause of failure. For example, we do this:
For causes 1 and 2, all the client code needs to know is that the service failed. We define a very simple "fatal error" fault contract that contains only a unique error ID. The full details of the error are logged on the server.
For cause 3, the end user needs to know exactly what he/she did wrong. We define a "validation errors" fault contract containing a collection of friendly error messages for the client code to display on screen.
We borrow the Microsoft EntLib class for cause 3, and use exception shielding to handle causes 1 and 2 declaratively. It makes for very simple code.
To Clarify:
We handle the three causes like this inside the service:
An unexpected exception is thrown in the service code. We catch it at the top level (actually exception shielding catches it, but the principle is the same). Log full details, then throw a FaultException<ServiceFault> to the client containing only the error ID.
We validate the input data and deliberately throw an exception. It's normally an ArgumentException, but any appropriate type would do. Once it is thrown, it is dealt with in exactly the same way as (1) because we want to make it appear the same to the client.
We validate the input data and deliberately throw an exception. This time, it's a FaultException<ValidationFault>. We configure exception shielding to pass this one through un-wrapped, so it appears on the client as FaultException<ValidationFault> not FaultException<ServiceFault>.
End result:
No catch blocks at all inside the service (nice clean code).
Client only has to catch FaultException<ValidationFault> if it wants to display messages to the user. All other exception types including FaultException<ServiceFault> are dealt with by the client's global error handler as fatal errors, since a fatal error in the service generally means a fatal error in the client as well.
It it is a common, routine failure, then throwing a fault is a mistake. The software should be written to handle routine items, like entering the wrong password. Fault processing is for exceptional failure which are not considered part of the program's normal design.
For example, if your program was written with the idea that it always has access to a database, and the database is not accessible, that's an issue where the "fix" is well outside of the limits of your software. A fault should be thrown.
Fault processing uses different logical flows through the structure of the programming language, and by using it only when you've "left" the normal processing of the programming problem, you will make your solution leverage the feature of the programming language in a way that seems more natural.
I believe it is good practice to separate error handling and fault handling. Any error case should be dealt by your program - fault handling is reserved for exceptional conditions. As a guide to the separation of the two I found it useful when considering such cases to remember that there are only three types of error (when handling data and messages) and only one type of fault.
The error types are related to different types of validation:
Message validation - you can determine from the message contents that the data is valid or invalid.
Example: content that is intended to be a date of birth - you can tell from the data whether it is valid or not.
Context validation - you can only determine that content is invalid by reference to the message
combined with the system state.
Example: a valid date of joining a company is earlier than that persons date of birth.
Lies to the system - you can only determine that a message was in error when a later message
throws up an anomaly.
Example: Valid date of birth stored and inspection of the person's birth certificate shows this to be incorrect. Correction of lies to the system generally require action outside of the system, for instance invoking legal or disciplinary remedies.
Your system MUST deal with all classes of error - though in case three this may be limited to issuing an alert.
Faults (exceptions) by contrast only have one cause - data corruption (which includes data truncation). Example: validation parameters are not passed.
Here the appropriate mechanism is fault or exception handling - basically handing off the problem to some other part of the system that is capable of dealing with it (which is why there should be an ultimate destination for unhandled faults).
In the old days we used to have a rule that exceptions were only for exceptional and unexpected things. One of the reasons you did not want to use them too much was that they "cost" alot of computing power.
But if you use exceptions you can reduce the amount of code, no need for alot of if else statements, just let the exception bubble up.
It depends on your project. The most important thing is that there is a project standard and everyone does it the same way.
My opinion is that exceptions/fault should be thrown whenever what the method is supposed to do can't be achieved. So validation logic should never raise exception except if the validation can't be made (i.e. for technical reasons) but never just because the data are not valid (in that case it will return validation codes/messages or anything helping the caller to correct the data).
Now the GetMember case is an interesting one because it's all about semantic. The name of the method suggest that a member can be retrieved by passing an id (compare to a TryGetMember method for exemple). Of course the method should not throw the same exception if the id is nowhere to be found or if the database does not respond but a wrong id passed to this method is probably the sign that something is going wrong somewhere before that call. Except if the user can directly enter a member-id from within the interface in which case a validation should occurred before calling the method.
I hear a lot about the performance issue. I just made a simple test using C# and trow/catch 1000 exceptions. The time it took is 23ms for 1K Exeptions. That's 23ยต per exception. I think performance is no longer the first argument here except if you plan to raise more than 2000 exception per second in which case you will have a 5% performance down, which I can start considering.
My humble opinion...