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 1 commit
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
6 changes: 6 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,12 @@
<artifactId>liquibase-maven-plugin</artifactId>
<version>4.23.1</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>

Choose a reason for hiding this comment

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

In Spring Boot it's better to choose starters over concrete dependencies, so I suggest to use validation starter

<artifactId>hibernate-validator</artifactId>
<version>8.0.1.Final</version>
</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
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
package mate.academy.bookstore.dto;

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import java.math.BigDecimal;
import lombok.Data;

@Data
public class CreateBookRequestDto {
@NotNull
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
private String author;
@NotNull
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.BAD_REQUEST);

Choose a reason for hiding this comment

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

Usually invalid arguments it's 422 response code. Also, define the common response format for the application and create a class with exception response body.

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