我有跟随REST控制器
import ...ApplicationUser
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
@RestController
@RequestMapping("/sign-up")
class SignUpController: BaseController() {
@ResponseStatus(HttpStatus.CREATED)
@PostMapping
fun signUp(@RequestBody applicationUser: ApplicationUser) {
applicationUser.password = bCryptPasswordEncoder.encode(applicationUser.password)
applicationUserRepository.save(applicationUser)
}
}
和模型/实体
import java.util.*
import javax.persistence.*
@Entity
class ApplicationUser(
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Long? = null,
@Column(unique = true)
var username: String? = null,
var password: String? = null
) {
@Column(unique = true)
var email: String? = null
...
}
所以,我有意地尝试user
用现有的保存email
,自然而然地
{
"timestamp": "2019-01-29T15:40:45.784+0000",
"status": 500,
"error": "Internal Server Error",
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"path": "/sign-up"
}
但这是有原因的,原因是(葡萄牙语,对不起,哈哈)
com.microsoft.sqlserver.jdbc.SQLServerException:违反UNIQUE KEY约束'UK_cb61p28hanadv7k0nx1ec0n5l'。无法在“ dbo.application_user”对象中插入重复的密钥。重复的键值为([email protected])。
那么,如何发送/加入/加入HTTP响应异常的原因呢?像这样
{
"timestamp": ...,
"status": ...,
"error": ...,
"message": ...,
"cause": "here is the cause of all problems",
"path": ...
}
这是可能的?感谢您的任何建议!
您可以使用ControllerAdvice处理此类异常。您可以配置它以捕获应用程序中的任何异常,然后返回适当的响应代码/消息。您可以在这里了解更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句