Matelutex
Matelutex

Reputation: 2220

How to validate path variable type: error 400 with wrong parameter and no logs in server, no error message

I have an endpoint:

@GetMapping("/v2/tw/{id}")
public TwDto getTw(Authentication auth, @PathVariable Long id) {
}

When I want to fetch data with Postman with wrong parameter type /v2/tw/variableNoNumber, then I want to have some logs in service, I want to get some validation error. How to do that?

Should I add eg. @NumberFormat? It doesn't work.

I use @ControllerAdvice, my project is quite old, everything is validated properly but THIS case is weird for me....

Upvotes: 1

Views: 1371

Answers (3)

Matelutex
Matelutex

Reputation: 2220

I think I found solution for my problem - instead of throwing 400 with some message maybe it would be sufficient to add:

@GetMapping("/v2/tw/{id:\d+}")
public TwDto getTw(Authentication auth, @PathVariable Long id) {
}

Then I get 404 error Not found and I think this approach is better than returning 400 error without any message... What do you think?

Upvotes: 1

Faramarz Afzali
Faramarz Afzali

Reputation: 795

You can write your custom exception handler.

  • This is your custom entity.

public class ApiException {
    private final String message;
    private final HttpStatus httpStatus;
 

    public ApiException(String message, HttpStatus httpStatus ) {
        this.message = message;
        this.httpStatus = httpStatus;
        this.timestamp = timestamp;
    }

    public String getMessage() {
        return message;
    }


    public HttpStatus getHttpStatus() {
        return httpStatus;
    }

    
}
  • This is your exception class.

public class ApiRequestException extends RuntimeException {

    public ApiRequestException(String message) {
        super(message);
    }

    public ApiRequestException(String message, Throwable cause) {
        super(message, cause);
    }

}
  • And finally ApiExceptionHandler
@ControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(value = {ApiRequestException.class})
    public ResponseEntity<Object> handleApiRequestException(ApiRequestException e) {
        HttpStatus badRequest = HttpStatus.BAD_REQUEST;
        ApiException apiException = new ApiException(e.getMessage(), badRequest));
        return new ResponseEntity<>(apiException, badRequest);
    }
}

For example, if you want to validate the ID you can write as below.

throw new ApiRequestException("Case by id" + TwDto.getId+ " was not found!");

Upvotes: 2

sourheart
sourheart

Reputation: 134

you can use the annotation @Valid for the parameter and handle the exception with the ConstraintViolationException. For more information and detail see here: https://medium.com/@aamine/customized-input-validation-in-spring-boot-1927aa440bc6

Upvotes: 0

Related Questions