6 springboot全局异常处理器?

6 springboot全局异常处理器?

异常前提知识

  1. 异常仅在线程内部传播
  2. 主线程未捕获异常 → 程序终止
  3. 子线程未捕获异常 → 仅终止该子线程,不影响主线程和其他线程
  4. 非守护线程退出,jvm会立即停止,无论是否有守护线程。

解决异常处理的方式之一:

  • 自定义类封装响应的格式(响应码、响应描述、响应结果数据)
  • 创建全局异常处理器GlobalExceptionHandler类

自定义类封装响应的格式(响应码、响应描述、响应结果数据)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class ErrorResponse {
    private int status;
    private String message;
    private Object details;
    private LocalDateTime timestamp = LocalDateTime.now();
    
    public ErrorResponse(int status, String message, Object details) {
        this.status = status;
        this.message = message;
        this.details = details;
    }
}

创建全局异常处理器GlobalExceptionHandler类

类加@RestControllerAdvice注解,方法加@ExceptionHandler(自定义异常.class )

创建全局异常处理器
java
@RestControllerAdvice
public class GlobalExceptionHandler {

    // 处理所有未捕获的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex) {
        ErrorResponse error = new ErrorResponse(
            HttpStatus.INTERNAL_SERVER_ERROR.value(),
            "服务器内部错误",
            ex.getMessage()
        );
        return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    // 处理自定义业务异常
    @ExceptionHandler(BusinessException.class)
    public ResponseEntity<ErrorResponse> handleBusinessException(
        BusinessException ex) {
        ErrorResponse error = new ErrorResponse(
            ex.getCode(),
            ex.getMessage(),
            ex.getDetails()
        );
        return new ResponseEntity<>(error, ex.getStatus());
    }

}
posted @ 2025-04-01 00:53  mikuc3c  阅读(48)  评论(0)    收藏  举报