Весенняя загрузка как я могу настроить исключение BadRequestException

#spring-boot #controller #spring-restcontroller

Вопрос:

Я создал класс BadRequestException и хочу показать это, когда контроллер вернет 400 ошибок. Но я не мог этого сделать.

Мой контроллер:

 @GetMapping("/{id}")
    public ResponseEntity<PostDto> getPostById(@PathVariable Long id) {
          if(!(id instanceof Long))
               throw new BadRequestException("your request is not valid !");
        return ResponseEntity.ok(restTemplateService.getPostById(id));
    }
 

Мой Общий Обработчик Исключений:

 @RestControllerAdvice
public class GeneralExceptionHandler extends ResponseEntityExceptionHandler {
    @NotNull
    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
                                                                  @NotNull HttpHeaders headers,
                                                                  @NotNull HttpStatus status,
                                                                  @NotNull WebRequest request) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach(error -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
    }


    @ExceptionHandler(PostNotFoundException.class)
    public ResponseEntity<?> postNotFoundExceptionHandler(PostNotFoundException exception) {
        return new ResponseEntity<>(exception.getMessage(), HttpStatus.NOT_FOUND);
    }


    @ExceptionHandler(BadRequestException.class)
    public ResponseEntity<?> badRequestExceptionHandler(BadRequestException exception) {
        return new ResponseEntity<>(exception.getMessage(), HttpStatus.BAD_REQUEST);
    }

}
 

Класс BadRequestException:

 @ResponseStatus(HttpStatus.BAD_REQUEST)
public class BadRequestException extends RuntimeException {
    public BadRequestException(String message) {
        super(message);
    }
}
 

Комментарии:

1. Это должно сработать просто отлично. Что не работает? Можете ли вы предоставить более подробную информацию?

2. if(!(id instanceof Long)) это условие никогда не будет истинным, если параметр не имеет типа Long, getPostById() он никогда не будет вызван.