Custom Exception Handling in Spring Boot with JSP - spring

I am new to Spring Boot with JSP development and I am a bit lost when it comes to handling exceptions.
This is my scenario:
User clicks on a User from the JSP
Through a path variable I retrieve user id.
I then pass the user id to a service class.
The service class will query for the user by connecting with the JPARepository
The place where I am confused is this.
If the returned object is a null, should I return that null object or should I throw a custom exception like ResourceNotFoundException and then have catch statements in the controller methods?
Please. Any help would be highly appreciated.

Related

Why is the JPA repository called from spring schedular not able to get the authentication from Security Context

I have a springboot application where with authentication available in SecurityContext post login. Any call from Rest Controller to persist any entity, getCurrentAuditor() method is called which returns the current principle which is used for auto updating the created date column.
I created an schedular using spring "awaitility" dependency. However, this schedular calls an update on a entity. When update is called and spring authentication is checked, it comes as null, even though i have logged in from front end. From front end i am able to persist other entities and gets the authentication object as well.
As per my understanding, this might be happening because the schedular starts as soon as Springboot kicks in and making save request independently. If that understanding is correct, how should i resolve this?
If the Scheduler can use a "system" user for update the entity, you can do something like the following and in the scheduler code perform the authentication:
public void authenticate() {
Authentication auth = authenticationManager.authenticate(getBatch());
SecurityContext sc = SecurityContextHolder.getContext();
sc.setAuthentication(auth);
}
public UsernamePasswordAuthenticationToken getBatch() {
return UsernamePasswordAuthenticationTokenBuilder.anUsernamePasswordAuthenticationToken()
.withCredentials(batchProperties.getPassword()).withUserCode(batchProperties.getUser()).withUserDto(
userDtoFactory.getBatch()).build();
}

Global Exception Handling via Spring Advice In a MQ based Spring Boot Application

I've a MQ Spring Boot PaaS application where I need to implement exception handling via a common exception handler class (GlobalExceptionHandler). My PaaS application receives message from a source queue, perform some database operations via spring jpa and write the response back to a destination queue.
I need to handle all the database RuntimeException, custom business exceptions and other checked exceptions via GlobalExceptionHandler class.
My GlobalExceptionHandler will have handlers (method) defined for every exception. In my handler, I will be logging the exception first and then I will be creating a [error code, desc] and then I need to return it back to main flow.
I do not have any controller in my application. So I think, I can't use #ControllerAdvice. Currently I'm using spring AOP #AfterThrowing as below but I'm not able to return the [code, desc] from handlers.
#AfterThrowing(pointcut = "execution(* com.abc.xyz.service..*(..)) ",
throwing = "dataNotFoundException")
public void handleDataNotFoundException(DataNotFoundException dataNotFoundException) {
LOGGER.info("Info : " + dataNotFoundException.getMessage());
// code, desc need to create here and send it back to calling place.
// I need to change the return type here from void.
}
Can anyone please guide me in implementing exception handling here.
As I explained here, #AfterThrowing cannot modify return values or otherwise change the execution flow of your epplication. You cannot even catch the exception there. You need to use an #Around advice instead.
I suggest you read some documentation first and then ask more follow-up questions.

Nullify some properties when getting the response from a method - Spring Security

I have the bellow apis in my application. My application manages spring security and in the logic there are some rules like based on the user's role , the user might be able to see or not certain attributes.
So my requirement it is to make null some attributes of the CustomObject based on the user's role.
Is there a way to accomplish this based with Spring Security ? There is the #PostFilter annotation but I think it will be useful to discard objects in the method's response , but not to make some attributes of the object null
public List<CustomObject> getCustomObjects()
public CustomObject getCustomObject()
If this is not possible with only spring security, I am thinking to create a custom annotation , mixed with some AOP to do the work, what do you think ?

ASP MVC N-Tier Exception handling

I am writing a service layer which uses Entity framework to get/set data from the database, and then pass it to an MVC web application. I am not able to decide what is the bext way to return database errors to the web application.
Should I throw an exception and the web application can handle it accordingly, or should I return a string/bool to convey that the database action has worked or not?
Any suggestion on what is the best practice?
Thanks
You can either not handle them in your service layer, or you can normalize them using an exception class that you will create. For example:
public class DatabaseException: Exception
{
public string TableName { get; private set; }
public DatabaseException(string tableName, Exception innerException)
:base("There a database error occured.", innerException)
{
TableName = tableName;
}
}
Simply add whatever information you require to the exception class as properties and initialize them in the constructor.
It's really not the best practice to inform the higher levels about exceptions with return values, since most of the methods are already returning some data.
You should not handle exception thrown out from web application, let exception thrown naturally, even from data access layer. With this way, it is easy for you for troubleshooting, esp in production stage. So, how to handle:
Use custom error page for exceptions thrown out.
Use HttpModule to log exception for troubleshooting. ELMAH, loggin module, works perfectly with ASP.NET MVC and alows you to view logs on web.

How to configure spring HandlerExceptionResolver to handle NullPointerException thrown in jsp?

From a jsp is thrown a NullPointerException for example using <% null.toString(); %>
This exception is not handled by the HandlerExceptionResolver, but thrown to the web container(tomcat) and converted into a code 500 error.
How can I configure spring to get that error in my HandlerExceptionResolver ?
Details:
Spring can be configured to handle exceptions thrown inside Controllers, but not exceptions thrown by view.
Of course i can resolve the NullPointerException, but i want to design a solution that will gracefully resolve any possible problem on the web application in order to display a user friendly message to the user.
See the HandlerInterceptor interface instead. You'll want the afterCompletion method. You can then intercept the response and then set the appropriate header information to redirect to a container-configured error web page. You're right that Spring doesn't have this functionality, this is going to have to be specified by the web.xml which determines which codes map to which pages.
I have not worked with this particular bit of the spring framework, but the docs say
"Interface to be implemented by objects than can resolve exceptions thrown during handler mapping or execution, in the typical case to error views. Implementors are typically registered as beans in the application context.
Error views are analogous to the error page JSPs, but can be used with any kind of exception including any checked exception, with potentially fine-granular mappings for specific handlers."
so I'd imagine that given that NullPointer extends RuntimeException the framework isn't designed to catch it. Is there a reason the exception(s) can't be handled in the controller directly?

Resources