竹简文档
异常处理

MySQL 异常处理

MysqlExceptionHandler 捕获 MySQL 数据库操作中的 SQL 语法错误与数据截断异常

MySQL 异常处理

MysqlExceptionHandler 专门处理 MySQL 数据库操作过程中产生的异常。该处理器独立于主异常处理继承链,通过自动配置注册。

MVC 与 WebFlux

本文档描述的异常映射表在 MVC 和 WebFlux 中完全一致。主要差异是返回类型:

  • MVC: ResponseEntity<BaseResponse<T>>
  • WebFlux: Mono<ResponseEntity<BaseResponse<T>>>

处理的异常类型

字段

类型

处理器结构

MysqlExceptionHandler.java
@RestControllerAdvice
public class MysqlExceptionHandler {

    @ExceptionHandler(SQLSyntaxErrorException.class)
    public ResponseEntity<BaseResponse<Void>> handleSqlSyntaxError(
            SQLSyntaxErrorException e) {
        // SQL 语法错误映射为服务器内部错误,避免暴露 SQL 细节
        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
        );
    }

    // 数据截断视为参数错误(客户端提交的数据不符合规范)
    @ExceptionHandler(MysqlDataTruncation.class)
    public ResponseEntity<BaseResponse<Void>> handleDataTruncation(
            MysqlDataTruncation e) {
        return ResultUtil.error(
            ErrorCode.PARAMETER_ERROR, e.getMessage(), null
        );
    }
}

典型场景

SQL 语法错误

当 MyBatis 动态 SQL 生成了无效的 SQL 语句时:

response.json
{
  "context": "550e8400-e29b-41d4-a716-446655440000",
  "output": "SERVER_INTERNAL_ERROR",
  "code": 50002,
  "message": null,
  "errorMessage": "You have an error in your SQL syntax",
  "duration": 12,
  "data": null
}

数据截断

当插入的数据超出字段长度限制时(例如 VARCHAR(50) 字段写入 100 字符):

response.json
{
  "context": "550e8400-e29b-41d4-a716-446655440000",
  "output": "PARAMETER_ERROR",
  "code": 40000,
  "message": null,
  "errorMessage": "Data truncation: Data too long for column 'username'",
  "duration": 8,
  "data": null
}

适用条件

该异常处理器仅在项目使用 MySQL 数据库时生效。若项目使用 PostgreSQL,请参阅 PostgreSQL 异常处理

下一步

On this page