spring rest Handling empty request body (400 Bad Request)

We Are Going To Discuss About spring rest Handling empty request body (400 Bad Request). So lets Start this Java Article.

spring rest Handling empty request body (400 Bad Request)

  1. spring rest Handling empty request body (400 Bad Request)

    In my case, I need to handle all requests that have invalid parameters. So I extend my class with ResponseEntityExceptionHandler and override the method handleMissingServletRequestParameter. You can find your own handlers defined inside the class ResponseEntityExceptionHandler

  2. spring rest Handling empty request body (400 Bad Request)

    In my case, I need to handle all requests that have invalid parameters. So I extend my class with ResponseEntityExceptionHandler and override the method handleMissingServletRequestParameter. You can find your own handlers defined inside the class ResponseEntityExceptionHandler

Solution 1

I solved the issue
(the custom exception handler must extend ResponseEntityExceptionHandler).
My solution follows:

        @ControllerAdvice
        public class RestExceptionHandler extends ResponseEntityExceptionHandler {
    
            @Override
            protected ResponseEntity<Object> handleHttpMessageNotReadable(
                HttpMessageNotReadableException ex, HttpHeaders headers,
                HttpStatus status, WebRequest request) {
                // paste custom hadling here
            }
        }

Original Author rvit34 Of This Content

Solution 2

In my case, I need to handle all requests that have invalid parameters. So I extend my class with ResponseEntityExceptionHandler and override the method handleMissingServletRequestParameter. You can find your own handlers defined inside the class ResponseEntityExceptionHandler

@ControllerAdvice 
public class YourExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(Exception.class)
    public final ResponseEntity handleAllExceptions(Exception ex) {
        // Log and return
    }

    @Override
    public ResponseEntity<Object> handleMissingServletRequestParameter(MissingServletRequestParameterException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        // Do your code here
        return new ResponseEntity<>("YOUR REQUEST PARAMS NOT MATCH!");
    } 
}

Original Author Nguyen Minh Hien Of This Content

Solution 3

I faced a similar issue and it didn’t work for me because the component-scanpackage provided didn’t include the package where my @ControllerAdvice was provided.

My XML had :

<context:component-scan base-package="com.bandi.rest" />

My package had a typo com.bandi.test.spring.exception. After changing it to com.bandi.rest.spring.exception it started working.

@ControllerAdvice
public class SpringRestExceptionHandler {

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public @ResponseBody ResponseEntity<ErrorResponse> handleNoMethodException(HttpServletRequest request,
            NoHandlerFoundException ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex);
        errorResponse.setErrorMessage("resource not found with exception");
        return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.NOT_FOUND);
    }

    @ExceptionHandler(Throwable.class)
    public @ResponseBody ResponseEntity<ErrorResponse> handleDefaultException(Throwable ex) {
        ErrorResponse errorResponse = new ErrorResponse(ex);
        errorResponse.setErrorMessage("request has empty body  or exception occured");
        return new ResponseEntity<ErrorResponse>(errorResponse, HttpStatus.BAD_REQUEST);
    }
}

Also, if you need to handle scenario where your requested resource was not found (bad URL), then you’ll have to add another configuration to your dispatcher servlet.

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>throwExceptionIfNoHandlerFound</param-name>
        <param-value>true</param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>
</servlet>

Complete Working code is available here

Original Author Kishore Bandi Of This Content

Solution 4

If You already have a class annotated with @ControllerAdvice and don’t want to create new one, You could use this piece of code:

@ExceptionHandler(HttpMessageNotReadableException.class)
public ResponseEntity<?> handleMissingRequestBody(Exception ex) {
    return handle(BAD_REQUEST, ex);
}

It should have the same behaviour as rvit34‘s solution.

Original Author Michal W Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment