package nju.seec.helper.controller; import lombok.extern.slf4j.Slf4j; import nju.seec.helper.controller.response.ErrorResponse; import nju.seec.helper.util.exception.HelperException; 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 java.util.Objects; /** * @author cst */ @Slf4j @RestControllerAdvice public class ControllerAdvice { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ErrorResponse.of(Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage())); } @ExceptionHandler(HelperException.class) public ResponseEntity handleHelperException(HelperException e) { return ResponseEntity.status(e.getType().getStatus()).body(ErrorResponse.of(e.getMsg())); } @ExceptionHandler(Exception.class) public ResponseEntity handleException(Exception e) { log.error(e.getLocalizedMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ErrorResponse.of("系统异常,请重试")); } }