Files
bbps-backend/src/main/java/com/billpaymentservice/bbps/exception/GlobalExceptionHandler.java
T

72 lines
2.8 KiB
Java

package com.billpaymentservice.bbps.exception;
import java.util.*;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;
import com.billpaymentservice.bbps.dto.ResponseModel;
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ResponseModel<?>> handleValidation(MethodArgumentNotValidException ex) {
List<Map<String, String>> fieldErrors = ex.getBindingResult().getFieldErrors()
.stream()
.map(fe -> Map.of("field", fe.getField(), "message", fe.getDefaultMessage()))
.collect(Collectors.toList());
logger.warn("Validation failed: {}", fieldErrors);
ResponseModel<List<Map<String, String>>> resp = new ResponseModel<>(
"Validation failed for request",
"FAILED",
HttpStatus.BAD_REQUEST.value(),
null
);
// put validation errors into data or duplicate field in ResponseModel as required
resp.setData(fieldErrors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
}
@ExceptionHandler(AppException.class)
public ResponseEntity<ResponseModel<?>> handleAppException(AppException ex) {
logger.warn("AppException: status={}, message={}", ex.getStatus(), ex.getMessage());
ResponseModel<?> resp = new ResponseModel<>(ex.getMessage(), ex.getStatus(), ex.getStatusCode(), ex.getData());
return ResponseEntity.status(HttpStatus.valueOf(ex.getStatusCode())).body(resp);
}
@ExceptionHandler(CustomException.class)
public ResponseEntity<ResponseModel<?>> handleCustomException(CustomException ex) {
logger.warn("CustomException: {}", ex.getMessage());
ResponseModel<?> resp = new ResponseModel<>(
ex.getMessage(),
"FAILED",
HttpStatus.BAD_REQUEST.value(),
null
);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(resp);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ResponseModel<?>> handleAll(Exception ex) {
logger.error("Unhandled exception", ex);
ResponseModel<?> response = new ResponseModel<>(
"Service temporarily unavailable. Please try again later.",
"FAILED",
HttpStatus.INTERNAL_SERVER_ERROR.value(),
null
);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}