Spring @ControllerAdvice处理异常,但不自定义响应
这是我的异常处理程序Spring @ControllerAdvice处理异常,但不自定义响应,spring,spring-boot,kotlin,error-handling,exception-handling,Spring,Spring Boot,Kotlin,Error Handling,Exception Handling,这是我的异常处理程序 @ControllerAdvice(basePackageClasses = [SignUpController::class]) class ControllerAdvice: ResponseEntityExceptionHandler() { @ExceptionHandler(Exception::class) @ResponseBody fun handleControllerException(request: HttpServletR
@ControllerAdvice(basePackageClasses = [SignUpController::class])
class ControllerAdvice: ResponseEntityExceptionHandler() {
@ExceptionHandler(Exception::class)
@ResponseBody
fun handleControllerException(request: HttpServletRequest, ex: Throwable): ResponseEntity<*> {
val status = HttpStatus.CONFLICT
return ResponseEntity<Any>(ApiError(status.value(), ex.message), status)
}
}
处理程序工作,但错误抛出如下
{
"timestamp": "2019-01-29T19:17:22.541+0000",
"status": 401,
"error": "Unauthorized",
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"path": "/sign-up"
}
{
"apierror": {
"status": ...,
"message": ..."
}
}
但我希望我能跟你一样
{
"timestamp": "2019-01-29T19:17:22.541+0000",
"status": 401,
"error": "Unauthorized",
"message": "could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement",
"path": "/sign-up"
}
{
"apierror": {
"status": ...,
"message": ..."
}
}
我是这个教程的基础
我做错了什么?我缺少任何配置?您需要用以下内容注释APIRROR类:
@Data
@JsonTypeInfo(
include = JsonTypeInfo.As.WRAPPER_OBJECT,
use = JsonTypeInfo.Id.CUSTOM,
property = "error",
visible = true
)
@JsonTypeIdResolver(LowerCaseClassNameResolver.class)
我的解决方法是,但不是正确答案 关于应用程序.yaml 在我的控制器上,我检查电子邮件和用户名是否存在,并向异常抛出自定义消息
@RestController
@RequestMapping("/register")
class RegisterController: BaseController() {
@ResponseStatus(HttpStatus.CREATED)
@PostMapping("/save")
fun register(@RequestBody user: ApplicationUser) {
if (userRepository.existsByEmail(user.email)) {
throw DataIntegrityViolationException("Email already exists")
}
if (userRepository.existsByUsername(user.username)) {
throw DataIntegrityViolationException("Username already exists")
}
user.password = bCryptPasswordEncoder.encode(user.password)
userRepository.save(user)
}
}
回报很好
{
"timestamp": "2019-01-31T17:08:40.832+0000",
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.DataIntegrityViolationException",
"message": "Email already exists", //here is
"path": "/register/save"
}
可能重复的