粘贴这段代码即可
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>
代码展示了如何在SpringBoot应用中使用`@ControllerAdvice`和`@ExceptionHandler`进行全局异常处理,包括捕获`Exception`和`MethodArgumentNotValidException`,并返回自定义的错误响应。同时,依赖于Spring的相关库和SLF4J日志框架。

被折叠的 条评论
为什么被折叠?



