package com.github.starhq.app.config.spring.exception; import java.util.HashMap; import…
- User
package com.github.starhq.app.config.spring.exception;
import java.util.HashMap; import java.util.Map;
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.github.starhq.app.config.spring.i18n.MessageUtils; import com.github.starhq.app.dto.RestResponse; import com.github.starhq.app.exception.DuplicateException;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor @RestControllerAdvice public class GlobalExceptionHandler {
private final MessageUtils messageUtils; @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationExceptions( MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getFieldErrors().forEach(error -> { errors.put(error.getField(), error.getDefaultMessage()); }); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); } @ExceptionHandler(DuplicateException.class) public ResponseEntity<RestResponse> handleDuplicateException( DuplicateException ex) { RestResponse response = messageUtils.buildErrorResponseWithArgs(ex, ex.getArgs(), "Duplicate resource"); return ResponseEntity.status(HttpStatus.CONFLICT).body(response); }} please optimize the code and add comments
- Assistant