如何在 Spring 启动中使用可分页界面从 http url 中删除/处理不相关或错误的排序参数?



如何在 Spring 启动中使用可分页界面从 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)

但是,可以使用各种类型处理异常。最终,您可以记录它或将其转换为任何自定义异常。根据我的要求,我已将其转换为自定义异常。

  1. 使用 AOP
@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");
}
}
}
  1. 使用@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);
}
}
  1. 控制器中的异常处理

将以下代码段添加到控制器

@ExceptionHandler({PropertyReferenceException.class})
public ResponseEntity<Void> handleAllExceptions(Exception ex, WebRequest req) 
{
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}

最新更新