Spring 带有 bean 验证的 JPA 存储库:错误响应不佳
Spring JPA-Repository with bean validation: Poor error response
我正在使用这样的模型对象:
@Entity
public class Address {
@Id
@GeneratedValue
private long id;
@NotNull
@Size(min = 1, max = 20)
private String location;
@OneToOne(mappedBy = "address")
private Person person;
}
有存储库
@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends PagingAndSortingRepository<Address, Long> {
}
当我尝试 post 破坏 bean 约束的对象时,我得到一个糟糕的错误响应:
{"timestamp":"2018-10-05T14:48:23.667+0000","status":500,"error":"Internal
Server Error","message":"Could not commit JPA transaction; nested
exception is javax.persistence.RollbackException: Error while
committing the transaction","path":"/address"}
如何在不自己实现每个 rest 控制器的情况下获得有用的错误消息?
定义控制器建议以全局处理异常,return您的自定义消息作为字符串或ErrorResponse
对象(您可以在其中定义自己的属性)。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RollbackException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public String handleRollbackException(RollbackException ex) {
String errorMessage = "Your custom message";
return errorMessage ;
}
}
我正在使用这样的模型对象:
@Entity
public class Address {
@Id
@GeneratedValue
private long id;
@NotNull
@Size(min = 1, max = 20)
private String location;
@OneToOne(mappedBy = "address")
private Person person;
}
有存储库
@RepositoryRestResource(collectionResourceRel = "address", path = "address")
public interface AddressRepository extends PagingAndSortingRepository<Address, Long> {
}
当我尝试 post 破坏 bean 约束的对象时,我得到一个糟糕的错误响应:
{"timestamp":"2018-10-05T14:48:23.667+0000","status":500,"error":"Internal Server Error","message":"Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Error while committing the transaction","path":"/address"}
如何在不自己实现每个 rest 控制器的情况下获得有用的错误消息?
定义控制器建议以全局处理异常,return您的自定义消息作为字符串或ErrorResponse
对象(您可以在其中定义自己的属性)。
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(RollbackException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public String handleRollbackException(RollbackException ex) {
String errorMessage = "Your custom message";
return errorMessage ;
}
}