0

I'm messing around on my rest application and I'm getting this error on my spring boot when my url parameters have some invalid characters in them:

http://myrestservice?[][][][]

then postman gives me this error.

java.lang.IllegalArgumentException: Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986 at

Is it possible to return a message instead of the server returning this exception?

I am only doing the rest services and no UI is involved.

askwer
  • 163
  • 13
  • Does this answer your question? [spring boot doesn't shows custom error pages](https://stackoverflow.com/questions/62727660/spring-boot-doesnt-shows-custom-error-pages) – Piotr P. Karwasz Aug 23 '21 at 05:18
  • More precisely: the server **does** return a `400` status code and error page to the client (which you can customize). The exception is logged for security purposes (is it an attack or a bug/misconfiguration in your application), but you can [disable it](https://stackoverflow.com/q/49190811/11748454). – Piotr P. Karwasz Aug 23 '21 at 05:33
  • 1
    Hi @PiotrP.Karwasz, thanks for commenting, the solution I ended up with is custom error pages. Thanks. – askwer Aug 23 '21 at 07:13
  • Rereading my comment I noticed that the suggested solution should not work for an incorrect URI path `/myrestservice/[]` (but I didn't test it). If you want to deal also with this case, you should mention it in the question. – Piotr P. Karwasz Aug 23 '21 at 07:19

1 Answers1

1

There is something you can achieve in spring boot by customizing your exception that is thrown from the controller. To do this,

  1. You have to create a separate class that extends the ResponseEntityExceptionHandler class.
  2. Annotate the class with the @ControllerAdvice.
  3. override handleMethodArgumentNotValid and handleHttpMessageNotReadable method. You can customize your exception and return it as a Response object with a proper error status code and message.
Raghu
  • 81
  • 5
  • I implemented this and handleHttpMessageNotReadable is working for invalid json input, however on invalid characters on the url, ex: myurl?[][][][] I still get the same error and the log message I put in handleHttpMessageNotReadable doesn't show up, it seems the error happens on the server itself and doesn't reach the application. – askwer Aug 23 '21 at 04:33
  • In the same class you can create one more method with the @ExceptionHandler({Exception.class}) annotation on the method and method return type as ResponseEntity. This method can take 2 arguments 1. Exception 2. Webrequest. You can try to customize your message here as well. – Raghu Aug 23 '21 at 04:44
  • @Raghu: the exception mentioned by the OP is thrown by Tomcat itself before reaching the controller. – Piotr P. Karwasz Aug 23 '21 at 04:57