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

Hw add global exception handler #7

Merged
merged 4 commits into from
Sep 11, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,11 @@
<artifactId>liquibase-core</artifactId>
<version>${liquibase.version}</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>7.0.5.Final</version>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package project.bookstore.controller;

import jakarta.validation.Valid;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
Expand Down Expand Up @@ -34,13 +35,13 @@ public BookDto getBookById(@PathVariable Long id) {
}

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

@PutMapping("/{id}")
public BookDto updateBook(
@RequestBody CreateBookRequestDto requestDto,
@RequestBody @Valid CreateBookRequestDto requestDto,
@PathVariable Long id
) {
return bookService.updateBook(requestDto, id);
Expand Down
10 changes: 10 additions & 0 deletions src/main/java/project/bookstore/dto/CreateBookRequestDto.java
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
package project.bookstore.dto;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.PositiveOrZero;
import java.math.BigDecimal;
import lombok.Getter;
import lombok.Setter;
import project.bookstore.validation.Unique;

@Getter
@Setter
public class CreateBookRequestDto {
@NotBlank
private String title;
@NotBlank
private String author;
@NotNull

Choose a reason for hiding this comment

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

Suggested change
@NotNull
@NotBlank

@Unique
private String isbn;
@NotNull
@PositiveOrZero
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 project.bookstore.exception;

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 {

Choose a reason for hiding this comment

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

Suggested change

@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);
List<String> errors = ex.getBindingResult().getAllErrors().stream()
.map(this::getErrorMessage)
.toList();
body.put("error", errors);
return new ResponseEntity<>(body, headers, status);

Choose a reason for hiding this comment

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

Suggested change
return new ResponseEntity<>(body, headers, status);
return new ResponseEntity<>(body, headers, HttpStatus.BAD_REQUEST);

}

private String getErrorMessage(ObjectError e) {
if (e instanceof FieldError) {
String fieldName = ((FieldError) e).getField();
String message = ((FieldError) e).getDefaultMessage();
return fieldName + ": " + message;
}
return e.getDefaultMessage();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,6 @@

public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {

boolean existsByIsbn(String isbn);

Choose a reason for hiding this comment

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

remove


}
17 changes: 17 additions & 0 deletions src/main/java/project/bookstore/validation/Unique.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package project.bookstore.validation;

import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Constraint(validatedBy = UniqueValidation.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Unique {

Choose a reason for hiding this comment

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

remove redundant validatot
you have unique constraint in Book entity
If you would like to check isbn, it's better to use regexp pattern

String message() default "This field is already exist!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
16 changes: 16 additions & 0 deletions src/main/java/project/bookstore/validation/UniqueValidation.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package project.bookstore.validation;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import project.bookstore.repository.BookRepository;

public class UniqueValidation implements ConstraintValidator<Unique, String> {
@Autowired
private BookRepository repository;

@Override
public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
return !repository.existsByIsbn(value);
}
}
Loading