Skip to content

Commit

Permalink
add project
Browse files Browse the repository at this point in the history
  • Loading branch information
WJ-Prajumsook committed Nov 22, 2019
1 parent 4d8ba4c commit e396a24
Show file tree
Hide file tree
Showing 15 changed files with 352 additions and 0 deletions.
31 changes: 31 additions & 0 deletions demoexception/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**
!**/src/test/**

### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache

### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr

### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/

### VS Code ###
.vscode/
11 changes: 11 additions & 0 deletions demoexception/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Spring Boot REST API Exception handling

### Reference
* Lombok
* MongoDB

### Hands-on coding
Show how to create custom exception and error message.



58 changes: 58 additions & 0 deletions demoexception/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>org.wj.prajumsook</groupId>
<artifactId>demoexception</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demoexception</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.wj.prajumsook;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoexceptionApplication {

public static void main(String[] args) {
SpringApplication.run(DemoexceptionApplication.class, args);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.wj.prajumsook.cofig;

import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import org.wj.prajumsook.entity.Book;
import org.wj.prajumsook.service.BookService;

import java.util.UUID;

@Log4j2
@Component
@Profile("local")
public class InitTestData implements ApplicationListener<ApplicationReadyEvent> {

@Autowired
private BookService service;

@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
service.deleteAll();
service.save(new Book(UUID.randomUUID().toString(), "Book Title", "Book author"));
log.info("One book saved");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package org.wj.prajumsook.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.wj.prajumsook.entity.Book;
import org.wj.prajumsook.service.BookService;

import java.util.List;

@RestController
@RequestMapping("/book")
public class BookController {

@Autowired
private BookService bookService;

@GetMapping
public List<Book> getAll() {
return bookService.getAll();
}

@GetMapping("/{id}")
public Book getBook(@PathVariable(value = "id") String id) {
return bookService.getById(id);
}

@DeleteMapping("/{id}")
public Book deleteById(@PathVariable(value = "id")String id) {
return bookService.deleteById(id);
}
}
18 changes: 18 additions & 0 deletions demoexception/src/main/java/org/wj/prajumsook/entity/Book.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.wj.prajumsook.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.mongodb.core.mapping.Document;

@Document
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Book {

private String id;
private String title;
private String author;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package org.wj.prajumsook.entity;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface BookRepository extends MongoRepository<Book, String> {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.wj.prajumsook.exception;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ApiException {

private String code;
private String type;
private String message;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package org.wj.prajumsook.exception;

import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@Log4j2
@ControllerAdvice
@RestControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {

@ExceptionHandler(BookNotFoundException.class)
public ResponseEntity<CustomerApiException> handleApiException(BookNotFoundException ex) {
logException(ex);
ApiException exception = new ApiException();
exception.setCode("error-000404");
exception.setType(HttpStatus.NOT_FOUND.toString());
exception.setMessage("No book found with id: " + ex.getId());
CustomerApiException customerApiException = new CustomerApiException(exception);

return new ResponseEntity<>(customerApiException, HttpStatus.NOT_FOUND);
}

@ExceptionHandler(Exception.class)
public ResponseEntity<CustomerApiException> handleException(Exception ex) {
logException(ex);
ApiException apiException = new ApiException();
apiException.setCode("error-000500");
apiException.setType(HttpStatus.INTERNAL_SERVER_ERROR.toString());
apiException.setMessage(ex.getMessage());

return new ResponseEntity<>(new CustomerApiException(apiException), HttpStatus.INTERNAL_SERVER_ERROR);
}

private void logException(Throwable t) {
StringBuilder sb = new StringBuilder();
for(StackTraceElement element : t.getStackTrace()) {
sb.append(element.toString());
sb.append("\n");
}

log.error("ERROR: [\n" + sb.toString() + "]");
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package org.wj.prajumsook.exception;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class BookNotFoundException extends RuntimeException {

private String id;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package org.wj.prajumsook.exception;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.List;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CustomerApiException {

private ApiException apiException;

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.wj.prajumsook.service;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.wj.prajumsook.entity.Book;
import org.wj.prajumsook.entity.BookRepository;
import org.wj.prajumsook.exception.BookNotFoundException;

import java.util.List;

@Service
@AllArgsConstructor
public class BookService {

private BookRepository repository;

public List<Book> getAll() {
return repository.findAll();
}

public Book getById(String id) {
return repository.findById(id).orElseThrow(() -> new BookNotFoundException(id));
}

public void deleteAll() {
repository.deleteAll();
}

public Book save(Book book) {
return repository.save(book);
}

public Book deleteById(String id) {
Integer.parseInt("xxx");
Book book = getById(id);
repository.deleteById(book.getId());

return book;
}
}
1 change: 1 addition & 0 deletions demoexception/src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
spring.profiles.active=local
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package org.wj.prajumsook;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class DemoexceptionApplicationTests {

@Test
void contextLoads() {
}

}

0 comments on commit e396a24

Please sign in to comment.