如何在spring boot中使用Pageable接口从http url中删除/处理不相关或错误的排序参数?
例如,我有一个类似 http://localhost:8080/all?sort=firstName,asc&sort=nosuchfield,asc的查询
如何处理或删除不相关的字段“nosuchfield”?
另外,如何限制 URL 中的排序参数?
如何在spring boot中使用Pageable接口从http url中删除/处理不相关或错误的排序参数?
例如,我有一个类似 http://localhost:8080/all?sort=firstName,asc&sort=nosuchfield,asc的查询
如何处理或删除不相关的字段“nosuchfield”?
另外,如何限制 URL 中的排序参数?
如果数据库中不存在排序字段,则 Spring JPA 将抛出以下异常。
org.springframework.data.mapping.PropertyReferenceException: No property nosuchfield found for type <TYPE>!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:94)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:382)
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:358)
但是,可以使用各种类型来处理异常。最终,您可以将其记录下来或将其转换为任何自定义异常。根据我的要求,我已将其转换为自定义异常。
@Aspect
@Component
public class UnKnownColumnSortingExceptionHandler {
@AfterThrowing(pointcut = "execution(* com.repositorypackage.*.*(..))", throwing = "exception")
public void executeWhenExceptionThrowninRepository(JoinPoint jp, Throwable ex) {
if (ex instanceof PropertyReferenceException) {
throw new CustomException("Invalid Database operation");
}
}
}
@ControllerAdvice(应用程序中的异常处理)@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
public GlobalExceptionHandler() {}
@ExceptionHandler({PropertyReferenceException.class})
public ResponseEntity<Void> handleAllExceptions(Exception ex, WebRequest req) {
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
将以下代码添加到您的控制器
@ExceptionHandler({PropertyReferenceException.class})
public ResponseEntity<Void> handleAllExceptions(Exception ex, WebRequest req)
{
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}