写个企业级的JdbcUtils
package com.grm.util;
import com.grm.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class JdbcUtils {
private static final String USERNAME = "root";
//数据库密码(本身不能明文写在项目中,此处简化了,先不考虑密码加密的问题)
private static final String PASSWORD = "root";
//驱动信息
private static final String DRIVER = "com.mysql.jdbc.Driver";
//数据库地址
private static final String URL = "jdbc:mysql://localhost:3306/mydb";
private Connection connection;
private PreparedStatement pstmt;
private ResultSet resultSet;
public JdbcUtils() {
try {
Class.forName(DRIVER);
} catch (Exception e) {
throw new BusinessException(500, "获取数据库连接驱动异常!");
}
}
public Connection getConnection() {
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
throw new BusinessException(500, "获取数据库连接异常!");
}
return connection;
}
public boolean insertOrUpdateOrDelete(String sql, List
其中业务异常类BusinessException
package com.grm.exception;
public class BusinessException extends RuntimeException {
private int code;
private String message;
public BusinessException(int code, String message) {
this.code = code;
this.message = message;
}
// getter setter
}
Springboot怎么捕获全局BusinessException呢
package com.grm.handler;
import com.grm.common.Result;
import com.grm.exception.BusinessException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.StringJoiner;
@RestControllerAdvice(annotations = RestController.class)
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
public Result errorHandler(HttpServletRequest req, Exception e) {
return Result.failed(500, e.getMessage());
}
@ExceptionHandler(value = BusinessException.class)
public Result businessExceptionHandler(HttpServletRequest req, Exception e) {
return Result.failed(500, e.getMessage());
}
}
评论列表(0条)