How to get a thrown exception from MailerClient of Playframework - playframework-2.5

I'm working with Play-Mailer inside of a Play application. I'm able to send emails to correct email addresses. So far so good. - But with none existing email addresses an exception is thrown from org.apache.commons.mailer but method mailerClient.send(email) itself throws nothing. - Is there a way to catch any exceptions form Play-Mailer?

EDIT:
I looked at the Play-Mailer plugin and saw that it is written in Scala. Scala does not have the notion of checked exceptions. Scala compiles directly to JVM bytecode and this is the "trick" how you can call Java code in Scala which throws checked exceptions but you do not have to rethrow them (the rules for checked exceptions are a bit different on JVM bytecode level).
You are free to use standard try-catch block in your Java code to handle the exceptions.
What kind of exceptions is the commons mailer throwing? Are you referring to: https://commons.apache.org/proper/commons-email/javadocs/api-release/org/apache/commons/mail/Email.html#send--
The send() methods throws an EmailException which is not a RuntimeException, so the exception would be propagated. If the Play-Mailer plugin is not catching it, you have to do it in your code:
try {
// try to send the mail
mailer.send(email);
} catch (EmailException e) {
// do something with the exception
}

Related

Exception handling with Kotlin with Spring

Roman Elizov has a great blog post on how to use exceptions with Kotlin. He emphasizes that catching exceptions in kotlin is usually code smell.
But does that mean that I should be able to throw exceptions freely in my Spring application if I am using application level exception handlers?
More specifically let's say I have function that looks up an item in the database, and a controller that calls this service. If the item is not in the database, should I return a nullable from the service or should I throw an exception? (The controller doesn't have to try/catch the exception because all applications are handled at framework level)
It depends on your use case and context. But generally I would say that you should throw an exception annotated with #ResponseStatus(HttpStatus.NOT_FOUND).

What is the replacement for Spring's deprecated NoSuchRequestHandlingMethodException?

The NoSuchRequestHandlingMethodException was deprecated in Spring 4.3, in favor of annotation-driven handler methods. What does this mean? The exception is still listed in the documentation, without mentioning its deprecated status. If I understand correctly, this exception is thrown when there is no request mapper for a given request. It appears to be handled by the DefaultExceptionHandlerResolver, here, and the relevant method has been deprecated as well.
If this method is deprecated, can I assume Spring does not throw this exception anymore? How am I supposed to replace this functionality with annotation-driven exception handling? Which exception am I supposed to handle, if this one is deprecated?
Side note: I also noticed a newer NoHandlerFoundException, here. Is this a replacement? If so, why? It appears to do the same thing. And why are the exceptions related to other HTTP status codes not deprecated? It all doesn't make a lot of sense.
The NoSuchRequestHandlingMethodException exception is part of the multiaction package that has been deprecated in Spring:
https://docs.spring.io/spring-framework/docs/2.5.x/javadoc-api/org/springframework/web/servlet/mvc/multiaction/class-use/NoSuchRequestHandlingMethodException.html
If you don't use multiactions, you can safely get rid of that catch statement and/or stop trying to catch and handle that exception. For example, some "Exception-to-Response error handlers" sample code might look like this to try and catch cases when the dispatcher doesn't find a proper mapping:
#ControllerAdvice
public class RestErrorHandler {
#ExceptionHandler({FileNotFoundException.class, NoSuchRequestHandlingMethodException.class})
#ResponseStatus(HttpStatus.NOT_FOUND)
#ResponseBody
public ErrorInfo process404(HttpServletRequest req, Exception ex) {
return handleException(req, HttpStatus.NOT_FOUND, ex);
}
}
But the latest dispatcher (non-multiaction) will never throw such an exception, so you could simply get rid of the NoSuchRequestHandlingMethodException and, instead, handle the NoHandlerFoundException (which is not thrown by default, but you can configure the spring dispatcher to throw it IF you really need to, because, by default, the dispatcher already returns a 404).

how to apply #ControllerAdvice in intellij idea?

i am working with intellij idea.
and i plan to make use of #ControllerAdvice to handle exceptions.
then intellij reports "unhandled exception", because i don't have a try-catch block in my code. then how to solve it? there must be a way.
If you're not going to handle the checked exceptions with a try catch, you'll need to rethrow the exception in the method signature. This will force the method that calls that method to handle the exception
public void someMethod() throws IOException {
}
https://docs.oracle.com/javase/tutorial/essential/exceptions/
Annotations can not affect language semantics. You may use #ControllerAdvice to handle exceptions at runtime, but they must be declared for the code to be accepted by the Java compiler.

Integrate GWT with Spring Security framework

I have searched for tutorials on this topics, but all of them are outdated. Could anyone provide to me any links, or samples about integrating Spring security into GWT?
First of all, you have to bear in mind that GWT application is turned into javascript running on client-side, so there is nothing you can really do about securing some resources out there. All sensitive information should be stored on server side (as in every other case, not only for GWT), so the right way is to think of Spring Security integration from the point of view of application services layer and integrating that security with communication protocol you use - in case of GWT it is request factory in most cases.
The solution is not very simple, but I could not do it in any better way... any refinement suggestions are welcome.
You need to start with creating GWT ServiceLayerDecorator that will connect the world of request factory with world of Spring. Overwrite createServiceInstance method taking name of spring service class to be invoked from ServiceName annotation value and return instance of this service (you need to obtain it from Spring ApplicationContext):
final Class<?> serviceClass = requestContext.getAnnotation(ServiceName.class).value();
return appContext.getBean(serviceClass);
Also, you need to override superclass invoke(Method, Object...) method in order to catch all thrown runtime exceptions.
Caught exception cause should be analyzed, if it's an instance of Spring Security AccessDeniedException. If so, exception cause should be rethrown. In such case, GWT will not serialize exception into string, but rethrow it again, thus, dispatcher servlet can handle it by setting appropriate HTTP response status code. All other types of exceptions will be serialized by GWT into String.
Actually, you could catch only GWT ReportableException, but unfortunately it has package access modifier (heh... GWT is not so easily extensible). Catching all runtime exceptions is much more safe (althouth not very elegant, we have no choice) - if GWT implementation change, this code will still work fine.
Now you need to plug in your decorator. You can do it easily by extending request factory servlet and defining your's servlet constructor as follows:
public MyRequestFactoryServlet() {
this(new DefaultExceptionHandler(), new SpringServiceLayerDecorator());
}
The last thing - you need to do a dirty hack and overwrite request factory servlet doPost method changing the way how it handles exceptions - by default, exception is serialized into string and server sends 500 status code. Not all exceptions should result in 500 s.c - for example security exceptions should result in unauthorized status code. So what you need to do is to overwrite exception handling mechanism in the following way:
catch (RuntimeException e) {
if (e instanceof AccessDeniedException) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
} else {
response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
LOG.log(Level.SEVERE, "Unexpected error", e);
}
}
Instead of extending classes, you can try to use some 'around' aspects - it is cleaner solution in this case.
That's it! Now you can annotate your application services layer as usual with Spring Security annotations (#Secured and so forth).
I know - it's all complicated, but Google's request factory is hardly extendable. Guys did a great work about communication protocol, but design of this library is just terrible. Of course the client-side code has some limitations (it is compiled to java script), but server-side code could be designed much better...

Handling exception when using HibernateDaoSupport

I am using Spring Hibernate integration in my application and DAO classes are extending HibernateDaoSupport.
Suppose I save some object using the code
getHibernateTemplate().save(object);
As Spring Hibernate integration doesn't mandate to write try-catch block, but suppose if any exception is thwron while saving that object.
Then what is the best way to handle it? I means should I catch it in the service layer and wrap it in some user defined excpetions.
Do I need to write try-catch in DAO layer method itself in case I want to log which method in DAO throws exception?
I have never used HibernateDaoSupport or Hibernate Template before so ignorant about exception handling. Please provide me your valuable inputs
The idea behind Spring using RuntimeException is that generally there are different types of exception:
Exceptions that you want to recover from (such as a DuplicateKeyException if a record that you're trying to insert already exists or the more general DataIntegrityViolationException if there was a DB constraint that was violated as a result of user input)
Exceptions that you can't recover from (the database is down)
For the first case, you may well handle the exception (either through a custom business exception, so that the view layer can redirect to the input page and provide a meaningful message)
For the second case, it would be easier to let the exception bubble up and have it handled by a generic exception handler that then displays a generic error page to the user. For this scenario it doesn't make sense to wrap the exception in a custom exception as you won't be able to recover. A blown up DB tends to be fatal.
So what I would do:
try {
getHibernateTemplate().save(object);
} catch (DataIntegrityViolationException dive) {
throw new BusinessValidationException(dive, "You've got the data wrong");
}
Spring exception hierarchy is well documented.
Usually you can't do much if you have a data access exception, because in the working system this may be caused by the shortage of diskspace on the DB server, or network connection problems etc.
Such exceptions are usually need to be logged and investigated as soon as possible.
There some recoverable errors, they can be handled with spring exception hierarchy, but imho most of them should be avoided during the developing phase, so your web server should validate as many things as possible, before it goes to the db.
If you want to set the exception logging see the similar questions:
Exception handler in Spring MVC
Spring MVC Best Practice Handling Unrecoverable Exceptions In Controller

Resources