异常处理
PostgreSQL 异常处理
PostgreSqlExceptionHandler 捕获 PostgreSQL 数据库操作中的 SQL 异常与数据截断异常
PostgreSQL 异常处理
PostgreSqlExceptionHandler 专门处理 PostgreSQL 数据库操作过程中产生的异常。该处理器独立于主异常处理继承链,通过自动配置注册。
MVC 与 WebFlux
本文档描述的异常映射表在 MVC 和 WebFlux 中完全一致。主要差异是返回类型:
- MVC:
ResponseEntity<BaseResponse<T>> - WebFlux:
Mono<ResponseEntity<BaseResponse<T>>>
处理的异常类型
字段
类型
处理器结构
@RestControllerAdvice
public class PostgreSqlExceptionHandler {
@ExceptionHandler(SQLSyntaxErrorException.class)
public ResponseEntity<BaseResponse<Void>> handleSqlSyntaxError(
SQLSyntaxErrorException e) {
return ResultUtil.error(
ErrorCode.SERVER_INTERNAL_ERROR, e.getMessage(), null
);
}
@ExceptionHandler(SQLException.class)
public ResponseEntity<BaseResponse<Void>> handleSqlException(
SQLException e) {
return ResultUtil.error(
ErrorCode.SERVER_INTERNAL_ERROR, e.getMessage(), null
);
}
// PSQLException 是 PostgreSQL JDBC 驱动的专有异常类
@ExceptionHandler(PSQLException.class)
public ResponseEntity<BaseResponse<Void>> handlePsqlException(
PSQLException e) {
return ResultUtil.error(
ErrorCode.SERVER_INTERNAL_ERROR, e.getMessage(), null
);
}
// 数据截断视为参数错误
@ExceptionHandler(DataTruncation.class)
public ResponseEntity<BaseResponse<Void>> handleDataTruncation(
DataTruncation e) {
return ResultUtil.error(
ErrorCode.PARAMETER_ERROR, e.getMessage(), null
);
}
}与 MySQL 处理器的差异
| 对比项 | MySQL | PostgreSQL |
|---|---|---|
| 驱动专有异常 | MysqlDataTruncation | PSQLException |
| 数据截断异常 | MysqlDataTruncation | DataTruncation(JDBC 标准) |
| 错误信息格式 | MySQL 错误码 + 消息 | PostgreSQL 状态码 + 详细消息 |
典型场景
PSQLException
当 PostgreSQL 约束违反时(如唯一键冲突):
{
"context": "550e8400-e29b-41d4-a716-446655440000",
"output": "SERVER_INTERNAL_ERROR",
"code": 50002,
"message": null,
"errorMessage": "ERROR: duplicate key value violates unique constraint \"user_email_key\"",
"duration": 10,
"data": null
}数据截断
当插入的数据超出字段长度限制时:
{
"context": "550e8400-e29b-41d4-a716-446655440000",
"output": "PARAMETER_ERROR",
"code": 40000,
"message": null,
"errorMessage": "ERROR: value too long for type character varying(50)",
"duration": 6,
"data": null
}适用条件
该异常处理器仅在项目使用 PostgreSQL 数据库时生效。若项目使用 MySQL,请参阅 MySQL 异常处理。