ControllerAdvice.java 1.4 KB

1234567891011121314151617181920212223242526272829303132333435
  1. package nju.seec.helper.controller;
  2. import lombok.extern.slf4j.Slf4j;
  3. import nju.seec.helper.controller.response.ErrorResponse;
  4. import nju.seec.helper.util.exception.HelperException;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.MethodArgumentNotValidException;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9. import org.springframework.web.bind.annotation.RestControllerAdvice;
  10. import java.util.Objects;
  11. /**
  12. * @author cst
  13. */
  14. @Slf4j
  15. @RestControllerAdvice
  16. public class ControllerAdvice {
  17. @ExceptionHandler(MethodArgumentNotValidException.class)
  18. public ResponseEntity<ErrorResponse> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
  19. return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ErrorResponse.of(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage()));
  20. }
  21. @ExceptionHandler(HelperException.class)
  22. public ResponseEntity<ErrorResponse> handleHelperException(HelperException e) {
  23. return ResponseEntity.status(e.getType().getStatus()).body(ErrorResponse.of(e.getMsg()));
  24. }
  25. @ExceptionHandler(Exception.class)
  26. public ResponseEntity<ErrorResponse> handleException(Exception e) {
  27. log.error(e.getLocalizedMessage());
  28. return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResponse.of("系统异常,请重试"));
  29. }
  30. }