Spring Boot logging - Don't log ConstraintViolationExceptions - spring

Here's my problem. I call a service method in the controller which is annotated with #Transactional. If this is comitted, a ConstraintViolationException occurs. I would like to catch it and put it into my own exception. Now I have the problem that I can catch the TransactionSystemException, but an error has already been logged. Can I prevent this somehow?
public ResponseEntity<T> update(String id, T obj) {
try {
return getResponseEntity(service.update(id, obj));
} catch (TransactionSystemException ex) {
System.out.println("CATCHED");
throw new InternalErrorException();
}
}
During my research I found out that I can disable logging for certain packages like
logging.level.org.springframework.dao.DataIntegrityViolationException=OFF
or
logging.level.org.hibernate.TransactionException=OFF
But that didn't help and I don't want to disable logging completely with logging.level.org.hibernate=OFF.

Please try to use #ControllerAdvice.
https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
https://medium.com/#jovannypcg/understanding-springs-controlleradvice-cd96a364033f

Related

How do we hook into After message processing using #RabbitListener

After checking the answer provided here (https://stackoverflow.com/a/34514526/6613150), I'm able to intercept the message before it's processed.
However, I now need to get it after the method who is annotated with #RabbitListener ends.
Any idea?
Add a MethodInterceptor advice to the container's advice chain instead. That way you have access to the Message before and after the listener call (and notification of any exception thrown).
try {
// before (message is in invocation arguments)
invocation.proceed();
// after
}
catch (Exception e) {
...
throw e;
}
finally {
...
}

Stop hibernate from throwing sensitive data when an exception is thrown

I am new to hibernate and Im using JPA +Hibernate + Spring Boot for my applications. The logging is being handled using log4j2 . When my application is correctly throwing an exception (in my case DataIntegrityViolationException or EntityExistsException) Hibernate is logging the exception with stackTrace. Which is great as it helps debug. However it also logs application sensitive data which I do not want to be present in the logs. Is there a setting in the properties file that can be set or modified to prevent this from happening. I don’t want to create an appender for hibernate in my log4j2.xml and mask specific words in the final log.
You can add global exception in spring boot and you can log the exception message only follow this tutorial - https://www.studytonight.com/spring-boot/spring-boot-global-exception-handling
Or you can do some try catch for each call and throw exception with your customized message as below.
Try {
//call
} catch (Exception ex){
throws CustomizedRunTimeException(“yourMessage”)
}
The class look like below
public class CustomizedRunTimeException extends RunTimeException {
public CustomizedRunTimeException(String errorMessage) {
super(errorMessage);
}
}

Quarkus hibernate validations exceptions not showing on the console

I have a simple project using Quarkus 1.4.2. When I use the #Valid annotation, and the validations fail with a status 500, the exception is not show on the console. Only in the Swagger UI. What should I do to print it out on the console?
#ApplicationScoped
public class ProductService {
public void validateProduct(#Valid Product product) {
}
}
The exception that is occurring is:
javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint
The error is correct. It is just not shown on the console.
I would expect the error to be logged as it's definitely a usability issue. And I would expect it to be logged on startup when we collect the Hibernate Validator metadata, not for every call.
You could create a reproducer and open a GitHub issue in the Quarkus tracker here.
I'll check it out and see if something needs fixing.
If I understand correctly, you need to use the Validator object in order to catch possible Exceptions:
#Inject
Validator validator;
public void validateProduct(Product product) {
// Should throw an error
Set<ConstraintViolation<Product>> violations = validator.validate(product);
if(violations.isEmpty()) {
return;
}
for (ConstraintViolation<Product> violation : violations) { // or log whole set as json
System.out.println(violation.toString()); //TODO prettify
}
throw new ValidationException(JsonbBuilder.create().toJson(violations));
}
If you get a 500 error, you can now catch it and log.
Or just catch UnexpectedTypeException where you call your service. This might be better.

if the exceptions have been swallowed, how does the spring aop log the exceptions' messages?

Here is my example bellow
public void test() throws Exception {
try {
int i = 1/0;
System.out.println(i);
} catch (Exception e) {
//the exception have been swallowed.
}
}
and the problem is spring aop's AfterThrowing can't work for this. if i remove the try-catch block.it works well then. how can i solve this problem. thanks for any suggestions.
Although it's unclear from question what you intend to achieve but this is the intended behavior of #AfterThrowing advice.
From docs -
After throwing advice runs when a matched method execution exits by throwing an exception.
which means that the advice will be executed only if an exception is thrown from method. In your sample the the exception is consumed and method exits normally thus no advice execution occurs.

Exception handling using hibernate template in Spring framework

I am using Spring with Hibernate in my project.There are many methods written in DAO implementation java file and every method is using the same try/catch/finally lines of code which seem redundant to me.
I am told to optimize/refactor the code since the file LOC exceeds 10k.I read somewhere that using HibernateDaoSupport we need not to worry about exceptions or closing the session. It will be taken care of by Spring itself.
Could somebody please help me how to proceed or do the needful or any better way to handle exceptions?I am pasting below code of one method in DAO layer.
public class CSDDaoImpl extends HibernateDaoSupport implements CSDDao {
public Deal getDealStructure(long dealId) throws CSDServiceException {
Session session = null;
try {
session = getSession();
Deal deal = (Deal) session.createCriteria(Deal.class).add(
Restrictions.eq("dealId", dealId)).uniqueResult();
return deal;
} catch (DataAccessResourceFailureException darfex) {
String message = "Failed to retrieve the deal object.";
CSDServiceException ex = new CSDServiceException(message, darfex);
ex.setStackTrace(darfex.getStackTrace());
ex.setErrorCode(Constants.DATA_ACCESS_FAILURE_EXP);
ex.setMessageToUser(message);
throw ex;
} catch (IllegalStateException isex) {
String message = "Failed to retrieve the deal object.";
CSDServiceException ex = new CSDServiceException(message, isex);
ex.setStackTrace(isex.getStackTrace());
ex.setErrorCode(Constants.ILLEGAL_STATE_EP);
ex.setMessageToUser(message);
throw ex;
} catch (HibernateException hbex) {
String message = "Failed to retrieve the deal object.";
CSDServiceException ex = new CSDServiceException(message, hbex);
ex.setStackTrace(hbex.getStackTrace());
ex.setErrorCode(Constants.HIBERNATE_EXP);
ex.setMessageToUser(message);
throw ex;
} finally {
if (session != null && session.isOpen()) {
try {
session.close();
} catch (HibernateException hbex) {
log.error("Failed to close the Hibernate Session.", hbex);
hbex.printStackTrace();
CSDServiceException ex = new CSDServiceException(
"Failed to close the Hibernate Session.", hbex);
ex.initCause(hbex.getCause());
ex.setStackTrace(hbex.getStackTrace());
throw ex;
}
}
}
}
}
The best approach of handling exceptions is i believe through writing an Exception Interceptor to intercept all your DAO calls and you can catch the ones you only need in your application and wrap it with your own custom application specific exceptions.
You definitely do not need to work directly with session once an exception is thrown. That would defeat the purpose of using HibernateDaoSupport and Spring.
Have a look at this link : http://static.springsource.org/spring/docs/current/spring-framework-reference/html/classic-spring.html
Hope that helps.

Resources