处理来自客户端的 Rest sql 异常

Handling Rest sql exception from client

我正在使用 spring 启动和 android。

我正在尝试使用 post 创建用户。对于积极的条件,它工作正常,但在消极的情况下,例如主键违规服务器抛出 sql 异常。

我想显示错误消息“客户端用户已存在”

这是一个验证检查场景,不是异常处理场景。您需要添加验证检查:
-> 首先在数据库中检查用户是否存在,如果存在则抛出错误。

我们在从用户那里获取输入时添加了验证检查。 当代码或受信任的客户端(例如我们的 UI 不涉及用户输入的应用程序逻辑)可能出现错误时,我们会进行异常处理。

用于处理异常并向客户端抛出一些消息。我们需要使用 @ControllerAdvice:
教程:exception-handling-with-controlleradvice
Spring 文档:exception handling in spring

这只是基于我的生产代码的模型(抱歉使用 Kotlin,如果 Java 您可以重新格式化):

  1. 创建统一的响应格式
data class Response @JsonCreator constructor (
    var message: String? = "",
    var success: Boolean = false,
    var data: Any? = null
)
  1. Return 作为控制器内的 ResponseEntity
@PostMapping
fun createUser(@ResponseBody newUser): ResponseEntity<Response> {
    return ResponseEntity(
        Response(
            "Create user: ",
            true,
            this.userService.createUser(newUser)
        ),
        HttpStatus.OK
    )
}
  1. 创建 CustomException 以抛出任何不需要的条件
class ResourceNotFoundException: RuntimeException {
    var statusCode: Int? = null

    constructor(errorMessage: String, statusCode:Int): super(errorMessage) {
        this.statusCode = statusCode
    }
    constructor(errorMessage: String, cause: Throwable, statusCode: Int): super(errorMessage, cause) {
        this.statusCode = statusCode
    }
}
  1. 创建用户,如果错误抛出自定义异常
fun createUser(newUser: UserEntity): Boolean { // can be replaced by any response
    try {
        this.userRepository.save(newUser)
    } catch (e: DuplicateKeyException) {
        throw ResourceNotFoundException(
            "Client user already exists",   // custom http message
            "404"  // custom http status
        )
    }
    return true
}
  1. 从 Android
  2. 捕获消息并将其显示给用户
showToast(response.message)

希望对您有所帮助