Home > Software engineering >  What is the proper way to control Required request body is missing Exception throwing?
What is the proper way to control Required request body is missing Exception throwing?

Time:09-16

I'm developing an API Service using Spring Boot with Maven. The problem is I want to control the Required request body is missing exception that is thrown to the client.

For example, I provide a API with POST method to the client. When the client call the API without Body. The Spring Boot will throw error in the body response like this,

{
    "timestamp": "2021-09-14T18:05:47.992 00:00",
    "status": 400,
    "error": "Bad Request",
    "trace": "org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.lang.Object>....
   ...
   ...
}

This will display the Controller name and line of code to the client. How can I just return some object to the client and like this,

{
    "message": "Required request body is missing"
}

Thank you for every helps.

CodePudding user response:

What you are looking for is a custom exception handler implementation. You need to override the following method in your custom exception handler.

The code would look somewhat like this:


@ControllerAdvice
@RestController
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleHttpMessageNotReadable(HttpMessageNotReadableException ex,
                                                              HttpHeaders headers,
                                                              HttpStatus status,
                                                              WebRequest request) {

      final MyMessageDto myExMsgDTO = new MyMessageDto("Required request body is missing");
      return new ResponseEntity(myExMsgDTO, headers, status);

}

}

Here, your MyMessageDto class can be a simple POJO like this:

public class MyMessageDto {
    private String message;

    public MyMessageDto(String message) {
        super();
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}

You can add more variables in the DTO class mentioned above to give more details in case of exception.

  • Related