how log and rethrow the entire class - java

I'm using spring.
I have a class with multiple methods. In each method I have to write:
public void method1(){
try{
//anything
}
catch(Exception e){
Log.error(e);
throw e;
}
}
public void method2(){
try{
//anything
}
catch(Exception e){
Log.error(e);
throw e;
}
}
public void method3(){
try{
//anything
}
catch(Exception e){
Log.error(e);
throw e;
}
}
public void method4(){
try{
//anything
}
catch(Exception e){
Log.error(e);
throw e;
}
}
Can I write something to don't have to write this in each method? Maybe an annotation?

Since you are using Spring, #ControllerAdvice would be a nice crispy solution for this case.
All you have to do is do some configuration and define your Global Exception handling class like so
#ControllerAdvice
public class ExceptionControllerAdvice {
// Handles Custom exceptions. MyException in this case
#ExceptionHandler(MyException.class)
public ModelAndView handleMyException(MyException mex) {
ModelAndView model = new ModelAndView();
...
return model;
}
// Handles all the exceptions
#ExceptionHandler(Exception.class)
public ModelAndView handleException(Exception ex) {
ModelAndView model = new ModelAndView();
model.addObject("errMsg", "This is a 'Exception.class' message.");
...
return model;
}
}
Refer to this post for configuring different types of error handling techniques in Spring.

If you just need to rethrow exception there are two solutions:
import lombok.SneakyThrows;
#SneakyThrows //annotation on method of lombok library
import static org.apache.commons.lang3.exception.ExceptionUtils.rethrow;
rethrow() //method from Apache commons library
1)
#SneakyThrows(Exception.class) //without specifying will rethrow all exceptions
public void method1(){
//anything
}
2)
public void method1(){
try{
//anything
}
catch(Exception e){
Log.error(e);
rethrow(e);
}
}

Related

How to regroup catch finally into one method in java 8?

New to java 8, I would like to optimise my code bellow:
public Response create() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
public Response update() {
try{
...
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
I have a lot of methods using this same way to catch exceptions and do the same finally, is that possible to replace the bellow common code by a method in java 8? So that I could optimise all my methods who use this common code.
} catch (Exception e) {
codeA;
} finally {
codeB;
}
Depends what you do in the .... You could do something like this:
private Response method(Supplier<Response> supplier) {
try{
return supplier.get();
} catch (Exception e) {
codeA;
} finally {
codeB;
}
}
and invoke like:
public Response create() { return method(() -> { ... for create }); }
public Response update() { return method(() -> { ... for update }); }
You could wrap your payload and put it to the separate method. One thing; what do you expect to return on exception catch. This time this is null, but probably you could provide default value.
public static <T> T execute(Supplier<T> payload) {
try {
return payload.get();
} catch(Exception e) {
// code A
return null;
} finally {
// code B
}
}
Client code could look like this:
public Response create() {
return execute(() -> new CreateResponse());
}
public Response update() {
return execute(() -> new UpdateResponse());
}
This could be a generic solution.
//here describe supplier which can throw exceptions
#FunctionalInterface
public interface ThrowingSupplier<T> {
T get() throws Exception;
}
// The wrapper
private <T> T callMethod(ThrowingSupplier<T> supplier) {
try {
return supplier.get();
} catch (Exception e) {
//code A
}finally {
// code B
}
}

Common Argument Pass in Method

I have a method called makePersistent in my DAO class.
Currntly we have this method in all dao classes and what i need to do is convert this method to common format. So is there any way to do it?
Method in UserDao Class
public void makePersistent(User model) throws InfrastructureException {
try {
getSession().saveOrUpdate(model);
getSession().flush();
getSession().clear();
} catch (org.hibernate.StaleObjectStateException ex) {
throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated"));
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
Method in HolidayDao Class
public void makePersistent(Holiday model) throws InfrastructureException {
try {
getSession().saveOrUpdate(model);
getSession().flush();
getSession().clear();
} catch (org.hibernate.StaleObjectStateException ex) {
throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated"));
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
Please help me to get rid of this redundant coding.
Thank you.
Just use Object the hibernate will persist it.
public void makePersistent(Object model) throws InfrastructureException {
try {
getSession().saveOrUpdate(model);
getSession().flush();
getSession().clear();
} catch (org.hibernate.StaleObjectStateException ex) {
throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdaed"));
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
Create a superclass for your DAOs with a type parameter and make your DAO classes extend that superclass with the appropriate type argument. For example:
public class BaseDao<T> {
public void makePersistent(T model) throws InfrastructureException {
try {
getSession().saveOrUpdate(model);
getSession().flush();
getSession().clear();
} catch (org.hibernate.StaleObjectStateException ex) {
throw new InfrastructureException(Labels.getString("com.tran.msg.objectDeletedOrUpdated"));
} catch (HibernateException ex) {
throw new InfrastructureException(ex);
}
}
}
public class UserDao extends BaseDao<User> {
// ...
}
public class HolidayDao extends BaseDao<Holiday> {
// ...
}
UserDao and HolidayDao inherit the makePersistent method from BaseDao, so you don't have to implement it again in every DAO class.

Catch a exception and show the user a warning about the failed operation

I have a DAO method which catches exceptions in order to perform a rollback of the transaction.
public void edit(Employees em) {
Session s = HibernateUtil.getSessionFactory().getCurrentSession();
try {
s.beginTransaction();
s.update(em);
s.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
s.getTransaction().rollback();
}
}
In the frontend, I'm invoking it as below.
public String save() {
Employee_dao dao = new Employee_dao();
dao.edit(emp);
return "index";
}
However, I would like to catch the exception in the frontend, so I can display a message to the enduser. How can I achieve this while still performing the rollback?
You can simply rethrow the exception, or even wrap it in an exception that contains more information if you need it at the frontend:
public void edit(Employees em) throws Exception {
// ...
try {
s.beginTransaction();
// ...
} catch (Exception e) {
s.getTransaction().rollback();
throw e;
// or throw new MyException("edit failed", e);
// or throw new RuntimeException(...);
}
}
public String save() {
Employee_dao dao = new Employee_dao();
try {
dao.edit(emp);
return "index";
} catch (Exception e) {
return "error";
}
}

How to specify a message on a method "throws" in Java?

Im trying to return a JOptionePane message dialog for each one of the possible throws on my method:
public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException{
... content ...
}
Is there any way to do this?
You could try something like :
public void add_note(String note) throws FileNotFoundException, IOException, InvalidFormatException
{
try
{
...content...
}
catch(FileNotFoundException fnfEx)
{
throw new FileNotFoundException("File was not found");
}
catch(IOException ioEx)
{
throw new FileNotFoundException("I/O exception");
}
catch(InvalidFormatException invEx)
{
throw new FileNotFoundException("Invalid format errror");
}
}
Where you put the message you want in the new exceptions and you print the exception message in the JOptionPane.
wrap your code inside try catch. Inside catch block for each exception type throw the message specific to each exception
Using a Try-Catch you can catch any exception and return something when an exception occurs. You should do this for all of your cases.
public void add_note(String note){
try {
//code
} catch (FileNotFoundException e) {
//return something
}
}
Instead of throwing exceptions, handle each individually in your method:
public JOptionPane add_note(String note) {
try {
...
} catch (FileNotFoundException fnfe) {
return ...;
} catch (IOException ioe) {
return ...;
} catch (InvalidFormatException ife) {
return ...;
}
}
I'll suggest you an alternative approach, as no one mentioned it.
I'd use AOP to catch those exceptions and show to the end user. You'll write a simple aspect, and dont mess your code with try and catch blocks.
Here is an example of such aspect
#Aspect
public class ErrorInterceptor{
#AfterThrowing(pointcut = "execution(* com.mycompany.package..* (..))", throwing = "exception")
public void errorInterceptor(Exception exception) {
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor started");
}
// DO SOMETHING HERE WITH EXCEPTION
logger.debug( exception.getCause().getMessage());
if (logger.isDebugEnabled()) {
logger.debug("Error Message Interceptor finished.");
}
}
}
If you don't know what Aspect Oriented Programming is definitely go check it out, this is very powerfull concept (just like OOP), spend some time to learn it.
If you want to show a dialog with the JOptionPane.showMessageDialog do as follows:
public void add_note(String note){
try {
//code
} catch (FileNotFoundException | IOException | InvalidFormatException e) {
JOptionPane.showMessageDialog(frame, e.getMessage(), "Title", JOptionPane.ERROR_MESSAGE);
//manage the exception here
}
}

Java IO Exception handling

when I debug the below code, there is an SmbException and goes catch block line sb.append(pLogger.reportError(pStr, e));, but it does not go into the method reportError().
what is the reason behind this. please advise if any changes.
try {
sfos = new SmbFileOutputStream(sFile);
} catch (SmbException e) {
sb.append(pLogger.rError(pathStr, e));
}
below is rError() method
public String rError(String pxString,Exception e){
String errorToMailStr=null;
abcd="Verifying # "+pxString+"::Error ["+e.getMessage()+"]";
logger.debug("Error when verifying # "+pxString+":Error ["+gMsg(e)+"]");
return abcd;
}
at line logger.debug("Issue "+pxString+":Error ["+gMsg(e)+"]");
is going to below method and ends.
public abstract class ReflectiveCallable {
public Object run() throws Throwable {
try {
return runReflectiveCall();
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
Based on what you have revealed here, there is a problem in getExceptionMsg()

Categories

Resources