0

I am trying to create a custom Exception handler which will be the first thing to run when a request is made for different endpoints using the same request body object.

Depending on the endpoint, It should check the request body object's fields and throw a different error message for the same field.

I could not figure out to specify the endpoint for @Valid and thought an Exception Handler would be a better solution for this issue.

My problem is on the Controller side. I could not figure out how to call the custom exception check when a request is made. Any help would be great.

public class RequestData {
  private String type; 
  private int distance;
  //getters, setters etc.
}

Controller:

    @RestController
    public class TestController {
        
        @PostMapping("/getSomething")
        @ExceptionHandler({CustomIllegalArgumentException.class})
        public ResponseEntity getSomething(@RequestBody RequestData requestData) {
              String endPoint = "getSomething";
            try {
                //first check requestData, if no exception is thrown then proceed.
                return new ResponseEntity<>("response", HttpStatus.OK);
            } catch (CustomIllegalArgumentException e) {
                return new RestExceptionHandler().handleIllegalRequestBodyException(requestData, e, endPoint);
            }
        }

        @PostMapping("/doSomething")
        @ExceptionHandler({CustomIllegalArgumentException.class})
        public ResponseEntity doSomething(@RequestBody RequestData requestData) {
            String endPoint = "doSomething";
            try {
                //first check requestData, if no exception is thrown then proceed.
                return new ResponseEntity<>("response", HttpStatus.OK);
            } catch (CustomIllegalArgumentException e) {
                return new RestExceptionHandler().handleIllegalRequestBodyException(requestData, e, endpoint);
            }
        }
    }

Custom Exception:

public class CustomIllegalArgumentException extends Exception {
}

Error Response Class:

@Getter
@Setter
public class ErrorResponse {

    private HttpStatus status;
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyyMMdd hh:mm:ss")
    private LocalDateTime timeStamp;
    private String message;

    public ErrorResponse(HttpStatus status) {
        this();
        this.status = status;
    }

    public ErrorResponse(HttpStatus status, String message) {
        this();
        this.status = status;
        this.message = message;
    }

    public ErrorResponse(){
        timeStamp = LocalDateTime.now();
    }
    public ErrorResponse(HttpStatus status, LocalDateTime timeStamp, String message) {
        this();
        this.status = status;
        this.timeStamp = timeStamp;
        this.message = message;
    }
}

Exception Handler For Custom Exception:

@ControllerAdvice
public class RestExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = CustomIllegalArgumentException.class)
public ResponseEntity handleIllegalRequestBodyException(RequestData requestData, CustomIllegalArgumentException exp, String endPoint) {
    ErrorResponse response = new ErrorResponse(HttpStatus.BAD_REQUEST);
    if(**endPoint.equals("doSomething")** && requestDdata.getDistance() > 2) {
        response.setMessage("a message for this endpoint");
    }
    if(**endPoint.equals("getSomething")** && requestDdata.getDistance() > 2) {
        response.setMessage("some other message for this endpoint");
    }

    return buildResponseEntity(response);
}

private ResponseEntity buildResponseEntity(ErrorResponse errorResponse) {
    return new ResponseEntity<>(errorResponse, errorResponse.getStatus());
}

}

Cugomastik
  • 911
  • 13
  • 22
  • You can validate the request with these annotations: https://stackoverflow.com/questions/36173332/difference-between-valid-and-validated-in-spring No need of a separate class. – Arun Sudhakaran Dec 16 '22 at 11:44
  • Hi Arun, Thank you for your answer. I thought about using @Valid but in my case, I have to return different error messages for different endpoints using the same Request Object. I am not sure if that is possible with the validation annotations. I have edited the question to minimize the confusion. – Cugomastik Dec 16 '22 at 12:27

0 Answers0