How can i swallow UnexpectedRollbackException? - spring-data-jpa

I was able to handle DataIntegrityViolationException which results from a duplicate constraint violation.
Since i am using #Transactional, i also receive a UnexpectedRollbackException which the app throws.
How can i handle/swallow the UnexpectedRollbackException ?

Related

What is better let database throw an execption or throw custom execption

I am developing an authentication system using express, So I have a unique email field in the database
should I check the email first and if it exists throw a new custom error Or let the database throw the error?
I want to know what is better
Consumers of your API don't and shouldn't know what kind of database you use.
The error that makes it back to them should encapsulate all of it and specifically tell them what is wrong in some standard format with a good HTTP status code.
Database-specific errors leaking to the user should usually be considered a bug.
Both.
You should write code to check that the email exists before you attempt the insert.
But if that check finds no email, you might still get an error, because of a race condition. For example, in the brief moment between checking for the email and then proceeding to insert the row, some other concurrent session may insert its own row using that email. So your insert will get a duplicate key error in that case, even though you had checked and found the email not present.
Then why bother checking? Because if you use a table with an auto_increment primary key, a failed insert generates and then discards an auto-increment value.
This might seem like a rare and insignificant amount of waste. Also, we don't care that auto-increment id's are consecutive.
But I did help fix an application for a customer where they had a problem that new users were trying 1500 times to create unique accounts before succeeding. So they were "losing" thousands of auto-increment id's for every account. After a couple of months, they exhausted the range of the signed integer.
The fix I recommended was to first check that the email doesn't exist, to avoid attempting the insert if the email is found. But you still have to handle the race condition just in case.

How and when to create a new JwtConsumerBuilder when keys in the HttpsJwks cache have gone stale

This question is in regards to the jose4j JWT library. I am planning to create a single JwtConsumerBuilder instance for processing all incoming requests. I read here on stackoverflow and in release notes that JwtConsumerBuilder is multi-thread safe. I also plan to use the setVerificationKey method to validate the signature. When the key expires, I assume I will get an exception. Which type of exception will be returned: InvalidJwtSignatureException or InvalidKeyException?
When such an exception occurs, my plan is to update my global instance of the JwtConsumerBuilder with a new instance after retrieving the updated key through the class HttpsJwksVerificationKeyResolver. Is this a sound approach or does the resolver take care of this for me.

Where to handle errors on database in mongoDB?

When user is registering on website, e-mail needs to be provided which is unique. I've made unique index on schema's email attribute, so if I try to save the document in database, error with code 11000 will be returned. My question is, regarding to business layer and data layer, should I just pass the document to database and catch/check error codes which it returns or should I check if the user with that e-mail exists before? I've being told that data integrity should be checked before passing it to the database by the business layer, but I don't see the reason why should I do that since I believe that mongo would be much faster raising the exception itself since it has that index provided. The only disadvantage I see in error code checking is that error codes might change (but I could abstract them) and the syntax might be changed.
There is the practical matter of speed and the fragility of "check-then-set" systems. If you try and check if an email exists before you write the document keyed on email, there is a chance that between the time you check and the time you right the conditions of the unique index are met and your write fails anyhow. This is a classic race condition. Further, it takes 2 queries to do check-then-set but only 1 query to do the insert and handle the failure. In my application I am having success with just letting the failure occur and reacting to the result.
As #JamesWahlin says, it is the difference between dong this all in one or causing mixed results (along with the index check) from potential race conditions by adding the extra client read.
Definitely rely on the response of only insert from MongoDB here.

How to handle Google Guava Cache refresh exceptions?

The Google Guava Cache documentation states:
Refreshing is not quite the same as eviction. As specified in LoadingCache.refresh(K), refreshing a key loads a new value for the key, possibly asynchronously. The old value (if any) is still returned while the key is being refreshed, in contrast to eviction, which forces retrievals to wait until the value is loaded anew.
If an exception is thrown while refreshing, the old value is kept, and
the exception is logged and swallowed.
This logging and swallowing of exceptions is really bad in my use case, because it means that if refresh throws an exception users of the cache will continue to find the stale data in the Cache.
How can I make sure that if an exception is thrown in refresh the cache starts returning null or calling load method?
If you never want to serve the stale data, you should call invalidate(key) instead of refresh(key). This discards the cached value for key, if one exists.
Then a subsequent call to get(key) will delegate synchronously to the value loader, and will rethrow any exception thrown by the CacheLoader, wrapped in an (Unchecked)ExecutionException.
If stale data is a problem for you then you should use expireAfterWrite to ensure that stale data is never served.

Logging logic and data errors in MVC3 with Elmah

I have a Service layer in my MVC3 app, which plays the role of a Repository among other things, as a layer between my Data layer and the actual web application. I have coded all my GetById methods to be robust, using FirstOrDefault and not just First, because the Id is passed in a URL and cannot be guaranteed to be a valid Id.
I now find myself where I'm doing a FirstOrDefault, then only proceeding if the result is not null. I would like to log the event when it is null, and then proceed to do nothing etc. Now, I am already using Elmah to log unhandled exceptions, and I have very little experience with exception handling etc. in MVC3, but it occurs to me that it might be better for me to use a simple First, with Elmah logging the exception if no entity is found.
How should I approach this scenario, where an invalid Id is quite definitely an logic exception, but not a low level CLR exception? This is not like when somebody is asked to enter an Id and no entity is found for their search term, which is a normal logic result.
Generating exceptions can be expensive. You're initial approach of validating user input is more robust. I would recommend using a logging framework such as NLog (http://nlog-project.org) to log the case were an invalid ID is passed in.
If you would like to keep all of your log messages in Elmah, then you can decide to write directly to Elmah's error log instead of bubbling-up an exception.