added retry for the send otp
This commit is contained in:
@@ -6,6 +6,7 @@ import java.util.stream.Collectors;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.http.*;
|
import org.springframework.http.*;
|
||||||
|
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||||
import org.springframework.validation.FieldError;
|
import org.springframework.validation.FieldError;
|
||||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
@@ -75,6 +76,35 @@ public class GlobalExceptionHandler {
|
|||||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ------------------------- MALFORMED/INVALID JSON ------------------------
|
||||||
|
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||||
|
public ResponseEntity<ResponseModel<?>> handleInvalidJson(
|
||||||
|
HttpMessageNotReadableException ex,
|
||||||
|
HttpServletRequest request,
|
||||||
|
HandlerMethod handlerMethod) {
|
||||||
|
|
||||||
|
String endpoint = (request != null) ? request.getMethod() + " " + request.getRequestURI() : "unknown";
|
||||||
|
// prefer the root Jackson message if present
|
||||||
|
String rootMsg = ex.getMostSpecificCause() != null ? ex.getMostSpecificCause().getMessage() : ex.getMessage();
|
||||||
|
String shortMsg = (rootMsg != null && rootMsg.length() > 200) ? rootMsg.substring(0, 200) + "..." : rootMsg;
|
||||||
|
|
||||||
|
logger.warn("Invalid JSON received for endpoint {}: {}", endpoint, shortMsg);
|
||||||
|
|
||||||
|
Map<String, Object> data = Map.of(
|
||||||
|
"exception", ex.getClass().getName(),
|
||||||
|
"message", shortMsg
|
||||||
|
);
|
||||||
|
|
||||||
|
ResponseModel<?> resp = new ResponseModel<>(
|
||||||
|
"[" + endpoint + "] Invalid JSON received",
|
||||||
|
"FAILED",
|
||||||
|
HttpStatus.BAD_REQUEST.value(),
|
||||||
|
data
|
||||||
|
);
|
||||||
|
|
||||||
|
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------------- NO HANDLER (404 NOT FOUND) ------------------------
|
// ------------------------- NO HANDLER (404 NOT FOUND) ------------------------
|
||||||
@ExceptionHandler(NoHandlerFoundException.class)
|
@ExceptionHandler(NoHandlerFoundException.class)
|
||||||
public ResponseEntity<ResponseModel<?>> handleNotFound(NoHandlerFoundException ex) {
|
public ResponseEntity<ResponseModel<?>> handleNotFound(NoHandlerFoundException ex) {
|
||||||
@@ -121,14 +151,17 @@ public class GlobalExceptionHandler {
|
|||||||
String context = buildErrorContext(ex, request, handlerMethod);
|
String context = buildErrorContext(ex, request, handlerMethod);
|
||||||
logger.warn("CustomException → {}", context);
|
logger.warn("CustomException → {}", context);
|
||||||
|
|
||||||
ResponseModel<?> resp = new ResponseModel<>(
|
// Use the ResponseModel carried by CustomException so callers get the original status/code/data
|
||||||
ex.getMessage(),
|
ResponseModel<?> resp = ex.getResponseModel();
|
||||||
"FAILED",
|
|
||||||
HttpStatus.BAD_REQUEST.value(),
|
|
||||||
null
|
|
||||||
);
|
|
||||||
|
|
||||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
|
HttpStatus httpStatus = HttpStatus.BAD_REQUEST;
|
||||||
|
try {
|
||||||
|
httpStatus = HttpStatus.valueOf(resp.getStatusCode());
|
||||||
|
} catch (Exception e) {
|
||||||
|
// fallback
|
||||||
|
}
|
||||||
|
|
||||||
|
return ResponseEntity.status(httpStatus).body(resp);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ------------------------- GENERIC EXCEPTION ------------------------
|
// ------------------------- GENERIC EXCEPTION ------------------------
|
||||||
|
|||||||
@@ -46,7 +46,7 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
public AuthServiceImpl(UserRepository userRepository, OtpClient otpClient, Helper helper,
|
public AuthServiceImpl(UserRepository userRepository, OtpClient otpClient, Helper helper,
|
||||||
UsersDetailsRepository userRepo, JwtUtil jwtUtil) {
|
UsersDetailsRepository userRepo, JwtUtil jwtUtil) {
|
||||||
this.userRepository = userRepository;
|
this.userRepository = userRepository;
|
||||||
this.otpClient = otpClient;
|
this.otpClient = otpClient;
|
||||||
this.helper = helper;
|
this.helper = helper;
|
||||||
@@ -56,21 +56,18 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public ResponseModel<?> sendOtp(LoginRequest request) {
|
public ResponseModel<?> sendOtp(LoginRequest request) {
|
||||||
try {
|
// validate minimal inputs
|
||||||
OtpSendResponse resp = otpClient.sendOtp(request.getMobile());
|
if (request == null || request.getMobile() == null || request.getMobile().isBlank()) {
|
||||||
if (resp == null) {
|
throw new CustomException("Mobile number is required", "FAILED", 400, "missing mobile");
|
||||||
return ResponseModel.builder().message("OTP send service returned null").status("Failure")
|
|
||||||
.statusCode(500).data(null).build();
|
|
||||||
}
|
|
||||||
String status = resp.isSuccess() ? "Success" : "Failure";
|
|
||||||
int code = resp.isSuccess() ? 200 : 400;
|
|
||||||
return ResponseModel.builder().message(resp.getMessage()).status(status).statusCode(code).data(resp)
|
|
||||||
.build();
|
|
||||||
} catch (Exception ex) {
|
|
||||||
LOGGER.error("Error in sendOtp: {}", ex.getMessage(), ex);
|
|
||||||
return ResponseModel.builder().message("An unexpected error occurred while sending OTP").status("Failure")
|
|
||||||
.statusCode(500).data(null).build();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Delegate attempts to helper — it will throw CustomException on unrecoverable issues
|
||||||
|
OtpSendResponse resp = attemptSendOtpWithRetry(request.getMobile(), 1);
|
||||||
|
|
||||||
|
// If the downstream returned a response indicating failure, return that as a ResponseModel
|
||||||
|
String status = resp.isSuccess() ? "Success" : "Failure";
|
||||||
|
int code = resp.isSuccess() ? 200 : 400;
|
||||||
|
return ResponseModel.builder().message(resp.getMessage()).status(status).statusCode(code).data(resp).build();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@@ -121,6 +118,40 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper that attempts to send OTP and retries up to `retryCount` times on null/unsuccessful responses.
|
||||||
|
* Throws CustomException when the OTP service returns null after retries or when unexpected errors occur.
|
||||||
|
*/
|
||||||
|
private OtpSendResponse attemptSendOtpWithRetry(String mobile, int retryCount) {
|
||||||
|
int attempts = 0;
|
||||||
|
OtpSendResponse resp = null;
|
||||||
|
while (attempts <= retryCount) {
|
||||||
|
attempts++;
|
||||||
|
try {
|
||||||
|
LOGGER.info("Attempt #{} to send OTP to {}", attempts, mobile);
|
||||||
|
resp = otpClient.sendOtp(mobile);
|
||||||
|
if (resp != null && resp.isSuccess()) {
|
||||||
|
LOGGER.info("OTP send succeeded on attempt #{} for {}", attempts, mobile);
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
// If response is non-null but indicates failure, we still may not want to retry for logical errors
|
||||||
|
if (resp != null && !resp.isSuccess()) {
|
||||||
|
LOGGER.warn("OTP service responded with failure on attempt #{} for {}: {}", attempts, mobile, resp.getMessage());
|
||||||
|
// Do not retry for application-level failures (invalid number etc.)
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
} catch (Exception ex) {
|
||||||
|
LOGGER.error("Exception while sending OTP on attempt #{} for {}: {}", attempts, mobile, ex.getMessage(), ex);
|
||||||
|
// continue to retry if attempts remain
|
||||||
|
}
|
||||||
|
// loop continues to retry if attempts <= retryCount
|
||||||
|
}
|
||||||
|
|
||||||
|
// After retries, if resp is null (no response received), treat as unrecoverable and let global handler handle it via exception
|
||||||
|
LOGGER.error("OTP service returned null after {} attempts for {}", attempts - 1, mobile);
|
||||||
|
throw new CustomException("OTP send service returned null", "FAILED", 500, "OtpClient returned null after retries");
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@Transactional
|
@Transactional
|
||||||
public ResponseModel<?> registerUser(RegisterRequest request) {
|
public ResponseModel<?> registerUser(RegisterRequest request) {
|
||||||
@@ -188,7 +219,7 @@ public class AuthServiceImpl implements AuthService {
|
|||||||
//
|
//
|
||||||
// if (user != null) {
|
// if (user != null) {
|
||||||
// userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getUserEmailId())
|
// userDetailsDTO = UserDetailsDTO.builder().id(user.getId()).userEmailId(user.getUserEmailId())
|
||||||
// .userMobNo(user.getUserMobNo()).userName(user.getUserName()).build();
|
// .userMobNo(user.getUserMobNo()).userName(user.getUserName()).build();
|
||||||
// }
|
// }
|
||||||
// AuthResponses authResp = new AuthResponses(token, "Success", "Login Done", 200, userDetailsDTO);
|
// AuthResponses authResp = new AuthResponses(token, "Success", "Login Done", 200, userDetailsDTO);
|
||||||
// return ResponseModel.builder().message("Login Done").status("Success").statusCode(200).data(authResp)
|
// return ResponseModel.builder().message("Login Done").status("Success").statusCode(200).data(authResp)
|
||||||
|
|||||||
Reference in New Issue
Block a user