0

How to remove/handle irrelevant or bad sort parameters from http url using Pageable interface in spring boot?

For e.g. I have a query like http://localhost:8080/all?sort=firstName,asc&sort=nosuchfield,asc

How can I handle or remove the irrelevant field "nosuchfield"?

Also, how can I limit sort parameters in URL?

1 Answers1

0

If the sorting field doesn't present in the database then below exception will be thrown by 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)

However, the exception can be handled using various types. Ultimately, you can just log it or transform it into any custom exception. As per my requirement, I have transformed it into a custom exception.

  1. Using 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. Using @ControllerAdvice(Exception handling in Application wise)
@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. Exception handling in Controller wise

Add the below piece of code to your controller

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

Prasanth Rajendran
  • 4,570
  • 2
  • 42
  • 59
  • How can we handle this error in restcontroller api? – Sharmistha Chakraborty May 19 '20 at 18:37
  • modified the answer as per your requirement – Prasanth Rajendran May 19 '20 at 20:08
  • Thank you will try the last one and will get back to you! – Sharmistha Chakraborty May 20 '20 at 06:09
  • Can we limit the sort parameters in controller or service level? – Sharmistha Chakraborty May 20 '20 at 06:10
  • `Iterator iterator = pageable.getSort().iterator();` , Pagable#getSort will provide you the iterator the requested fields and you can set the size limit check or any other business condition in your Service class – Prasanth Rajendran May 20 '20 at 14:39
  • Spring is not throwing any exception for invalid sort params. I am using MongoRepository. How to handle field exceptions in mongodb? Also I need to limit or handle the sort parameters in a config file not in controller...how can i globalise that? – Sharmistha Chakraborty May 21 '20 at 11:39
  • Surely it will throw an exception for an unknown column name, and I don't find any out-of-the-box sorting properties related to limit the sorting `https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#data-properties` – Prasanth Rajendran May 21 '20 at 13:14
  • I am trying to implement using this: – Sharmistha Chakraborty May 21 '20 at 15:41
  • The controller call bypasses the non existing sorting fields meaning instead of throwing exception its ignores the invalid sort fields and returns unsorted result. I believe Pageable implementation doesn’t help in throwing exception. How can I replace default SortArgumentResolver meaning how can I use resolvearguement method of SortArguementHandlerResolver class and include it inPageableArguementHandlerResolver class to limit and handle the invalid sort fields?Please provide some code example . – Sharmistha Chakraborty May 22 '20 at 01:44
  • I have implemented this. Its working. But I am not sure how to propagate the exception from the Customized SortArguementHandlerResolver class to Controller method. – Sharmistha Chakraborty May 23 '20 at 11:56
  • Have implemted a workng soln. But not sure how to propagate the exception from the CustomizedSortArguementHandlerResolver class to handler method in Controller class. @Override public Sort resolveArgument(MethodParameter methodParameter,ModelAndViewContainer modelViewContainer, NativeWebRequest nativeWebRequest,WebDataBinderFactory webDataBinderFactory) { ....//some logic.... if (orders.size() >= 2) { throw new InvalidSortException(); } catch (Exception e) { e.msg}return sort; } – Sharmistha Chakraborty May 23 '20 at 12:11
  • I hope you would have tried the `@ExceptionHandler({InvalidSortException.class})`, doesn't help it for your case? – Prasanth Rajendran May 27 '20 at 17:31