粘贴这段代码即可
package tech.mybatis.plus.springboot.study.details.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import tech.mybatis.plus.springboot.study.details.response.ErrorResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<?> handleException(Exception e) {
Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
log.error("Unhandled exception occurred", e);
ErrorResponse errorResponse = new ErrorResponse(Collections.singletonList("An unexpected error occurred"));
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
List<ObjectError> errors = e.getBindingResult().getAllErrors();
ErrorResponse errorResponse = new ErrorResponse(errors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList()));
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse);
}
}
这个是 tech.mybatis.plus.springboot.study.details.response.ErrorResponse;
import java.util.List;
public class ErrorResponse {
private List<String> errors;
public ErrorResponse(List<String> errors) {
this.errors = errors;
}
public List<String> getErrors() {
return errors;
}
public void setErrors(List<String> errors) {
this.errors = errors;
}
}
maven中添加如下配置:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.8</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.32</version>
</dependency>