Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added data validation and global exception handler #4

Merged
merged 3 commits into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@
<artifactId>liquibase-maven-plugin</artifactId>
<version>4.23.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

</dependencies>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package mate.academy.bookstore.controller;

import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import mate.academy.bookstore.dto.BookDto;
Expand Down Expand Up @@ -31,13 +32,13 @@ public BookDto getBookById(Long id) {
}

@PostMapping
public BookDto createBook(@RequestBody CreateBookRequestDto bookDto) {
public BookDto createBook(@RequestBody @Valid CreateBookRequestDto bookDto) {
return bookService.save(bookDto);
}

@PutMapping("/{id}")
public BookDto updateBook(@PathVariable Long id,
@RequestBody CreateBookRequestDto requestDto) {
@RequestBody @Valid CreateBookRequestDto requestDto) {
return bookService.update(id, requestDto);
}

Expand Down
16 changes: 16 additions & 0 deletions src/main/java/mate/academy/bookstore/dto/CreateBookRequestDto.java
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
package mate.academy.bookstore.dto;

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.math.BigDecimal;
import lombok.Data;
import org.hibernate.validator.constraints.ISBN;

@Data
public class CreateBookRequestDto {
@NotNull
@NotEmpty
@Size(max = 255)
private String title;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Validate the size of title to not allow empty titles and to not exceed the maximum size set by DB schema, the same for author field

@NotNull
@NotEmpty
@Size(max = 255)
private String author;
@NotNull
@NotEmpty
@ISBN
private String isbn;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can use ISBN annotation

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isbn has other validation rule except of not null (see Oleg's suggestion)

@NotNull
@Min(0)
private BigDecimal price;
private String description;
private String coverImage;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package mate.academy.bookstore.exceptions;

import java.time.LocalDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {

@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex,
HttpHeaders headers,
HttpStatusCode status,
WebRequest request
) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.UNPROCESSABLE_ENTITY);
List<String> errors = ex.getBindingResult().getAllErrors().stream()
.map(this::getErrorMessage)
.toList();
body.put("errors", errors);
return super.handleMethodArgumentNotValid(ex, headers, status, request);
}

private String getErrorMessage(ObjectError e) {
if (e instanceof FieldError) {
String field = ((FieldError) e).getField();
String message = e.getDefaultMessage();
return field + " " + message;
}
return e.getDefaultMessage();
}
}
Loading