E
E
EgorSvinarev2021-07-31 09:16:03
Java
EgorSvinarev, 2021-07-31 09:16:03

How to handle AuthenticationException in controller?

Hello. There is a service method that throws an exception that inherits from AuthenticationException and that is responsible for the authentication process.

Service

public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    
    Optional<User> user = repository.findByUsername(username);
    
    if (user.isEmpty()) {
      throw new UsernameNotFoundException("The user wasn't found.");
    }
    
    return user.get();
}



The question is how to handle this exception so that we get the message from the exception and put it into the view?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-07-31
Hasanly @azerphoenix

Good afternoon!
Exceptions can be handled at the global level with @ControllerAdviceor handled at the controller level.
Pay attention to the section "Global Exception Handling" at the link below
Here, here is a link to a useful article on your question:
https://spring.io/blog/2013/11/01/exception-handli...
Pay attention to the section - Controller Based Exception Handling@ExceptionHandler

The question is how to handle this exception so that we get the message from the exception and put it into the view?

It's best not to expose your application's internal state (exceptions) to the front, as this could potentially break your application's security. Catch the exception and put another message in the view. For example, "Authentication failed"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question