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 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
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.Pattern;
import jakarta.validation.constraints.PositiveOrZero;
import java.math.BigDecimal;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class CreateBookRequestDto {
@NotBlank
private String title;
@NotBlank
private String author;
@NotBlank
@Pattern(regexp = "//d{13}", message = "Should be a valid ISBN number: 13 numbers only!")
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,45 @@
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 {
@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, HttpStatus.BAD_REQUEST);
}

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

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

}
Loading