如何在HTTP请求异常上引发CAUSE

时间:2019-01-29 16:05:24

标签: sql spring hibernate spring-boot kotlin

我有关注的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:已修复   唯一键'UK_cb61p28hanadv7k0nx1ec0n5l'。 Nãoépossívelinserir uma   否否'dbo.application_user'。查瓦尔   duplicadaé(admin@email.com)。

那么,如何发送/提交/加入HTTP响应异常的原因?像这样

{
    "timestamp": ...,
    "status": ...,
    "error": ...,
    "message": ...,
    "cause": "here is the cause of all problems",
    "path": ...
}

有可能吗?感谢您的任何建议!

1 个答案:

答案 0 :(得分:1)

您可以使用ControllerAdvice处理此类异常。 您可以配置它以捕获应用程序中的任何异常,然后返回适当的响应代码/消息。您可以详细了解here