Spring Boot传入错误UUID返回400而非自定义异常的解决问询
问题原因
Spring MVC在请求到达控制器方法前,会自动执行参数类型转换。当路径参数{id}无法转换为UUID类型时,参数解析器会直接抛出TypeMismatchException,请求根本不会进入你的getCustomer方法,所以方法内的自定义异常逻辑完全无法触发。
解决方案
方案1:手动处理参数转换(简单直接)
将路径参数类型改为String,在方法内手动转换为UUID,转换失败时抛出自定义异常:
@GetMapping("/customer/{id}") fun getCustomer(@PathVariable id: String): ResponseEntity<ApiResponse<Customer>> { // 手动转换并校验UUID格式 val uuid = try { UUID.fromString(id) } catch (e: IllegalArgumentException) { throw IncorrectUUIDException("Invalid ID: $id") } val customer = customerService.getCustomer(uuid) if(customer.code == ResultCode.FETCH_FAILURE) { throw IncorrectUUIDException("Invalid ID: $id") } return ResponseEntity.ok().body( ApiResponse( entity = customer.entity ) ) }
方案2:全局异常捕获(适合多接口统一处理)
通过@RestControllerAdvice定义全局异常处理器,捕获Spring抛出的TypeMismatchException,并转换为自定义异常的响应格式:
@RestControllerAdvice class GlobalExceptionHandler { // 处理UUID类型转换失败的情况 @ExceptionHandler(TypeMismatchException::class) fun handleUUIDTypeMismatch(e: TypeMismatchException): ResponseEntity<ApiResponse<Any>> { if (e.requiredType == UUID::class.java) { val invalidId = e.value?.toString() ?: "unknown" return ResponseEntity.badRequest().body( ApiResponse( message = "Invalid ID: $invalidId", code = ResultCode.INVALID_PARAM // 替换为你的业务错误码 ) ) } // 处理其他类型不匹配的情况 return ResponseEntity.badRequest().body( ApiResponse( message = "Invalid parameter type", code = ResultCode.INVALID_PARAM ) ) } // 处理自定义的IncorrectUUIDException @ExceptionHandler(IncorrectUUIDException::class) fun handleIncorrectUUID(e: IncorrectUUIDException): ResponseEntity<ApiResponse<Any>> { return ResponseEntity.badRequest().body( ApiResponse( message = e.message, code = ResultCode.INVALID_PARAM ) ) } }
方案选择
- 如果只是单个接口需要处理UUID格式校验,优先选方案1,代码侵入性低,逻辑直观。
- 如果多个接口都有UUID类型的路径参数,优先选方案2,可以统一管理参数校验逻辑,避免重复代码。
内容的提问来源于stack exchange,提问作者JamieRhys
相关产品推荐
相关产品推荐

