I have created a custom exception class
public class DataException extends Exception {
private final String errorCode;
private final String errorMessage;
private final HttpStatus httpStatus;
/**
*/
public DataException( String errorCode, String errorMessage,
HttpStatus httpStatus )
{
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.httpStatus = httpStatus;
}
And I am sending this exception class to the client side when an exception is thrown. I am also using Spring-Security and JWT
for Authentication and Authorization
process.
When a user logs in to the application by hitting endpoint /rest/login
, and if the credentials are wrong, spring is throwing its exception which is going to the client side.
How to catch that exception thrown by security filter and create our User defined exception and send it to the client side?
My filter method,
@Override
public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response )
{
try
{
UserModel credentials = new ObjectMapper().readValue(request.getInputStream(), UserModel.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(credentials.getEmailId(),
credentials.getPassword(), new ArrayList<>()));
}
catch( IOException | AuthenticationException e )
{
LOGGER.error("Exception", "Invalid EmailId/Password");
throw new BadCredentialsException("Invalid EmailId/password");
}
}