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

Exception mapping #24

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 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
6 changes: 5 additions & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@
<artifactId>quarkus-hibernate-orm</artifactId>
</dependency>

<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-hibernate-validator</artifactId>
</dependency>

<!-- JDBC driver dependencies -->
<dependency>
<groupId>io.quarkus</groupId>
Expand Down Expand Up @@ -239,7 +244,6 @@
</execution>
</executions>
</plugin>

</plugins>
</build>
<profiles>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ public abstract class ApplicationPersistenceEntity {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Version
private Integer modificationCounter;

/**
Expand All @@ -42,7 +43,6 @@ public void setId(Long id) {
this.id = id;
}

@Version
public Integer getModificationCounter() {

return this.modificationCounter;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.devonfw.quarkus.general.service.exception;

public abstract class ApplicationBusinessException extends RuntimeException {

public ApplicationBusinessException() {

super();
}

public ApplicationBusinessException(String message) {

super(message);
}

public ApplicationBusinessException(String message, Exception e) {

super(message, e);
}

public boolean isTechnical() {

return false;
}

public String getCode() {

return getClass().getSimpleName();
}

public Integer getStatusCode() {

return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package com.devonfw.quarkus.general.service.exception;

public class InvalidParameterException extends ApplicationBusinessException {

public InvalidParameterException() {

super();
}

public InvalidParameterException(String message) {

super(message);
}

@Override
public Integer getStatusCode() {

return Integer.valueOf(422);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.devonfw.quarkus.general.service.exception;

import java.time.ZonedDateTime;
import java.util.HashMap;
import java.util.Map;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import lombok.extern.slf4j.Slf4j;

@Provider
@Slf4j
public class RestServiceExceptionFacade implements ExceptionMapper<RuntimeException> {

private boolean exposeInternalErrorDetails = false;

@Context
UriInfo uriInfo;

@Override
public Response toResponse(RuntimeException exception) {

log.error("Exception:{},URL:{},ERROR:{}", exception.getClass().getCanonicalName(), this.uriInfo.getRequestUri(),
exception.getMessage());

if (exception instanceof ApplicationBusinessException) {
return createResponse((ApplicationBusinessException) exception);
} else if (exception instanceof WebApplicationException) {
return createResponse((WebApplicationException) exception);
}

return createResponse(exception);
}

private Response createResponse(ApplicationBusinessException exception) {

int status = exception.getStatusCode() == null ? Status.BAD_REQUEST.getStatusCode() : exception.getStatusCode();
return createResponse(status, exception.getCode(), exception);
}

private Response createResponse(WebApplicationException exception) {

Status status = Status.fromStatusCode(exception.getResponse().getStatus());
return createResponse(status.getStatusCode(), exception.getClass().getSimpleName(), exception);
}

private Response createResponse(Exception exception) {

return createResponse(Status.INTERNAL_SERVER_ERROR.getStatusCode(), exception.getClass().getSimpleName(),
exception);
}

private Response createResponse(int status, String errorCode, Exception exception) {

Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("errorCode", errorCode);
if (this.exposeInternalErrorDetails) {
jsonMap.put("message", getExposedErrorDetails(exception));
} else {
jsonMap.put("message", exception.getMessage());
}
jsonMap.put("uri", this.uriInfo.getPath());
jsonMap.put("timestamp", ZonedDateTime.now().toString());
return Response.status(status).type(MediaType.APPLICATION_JSON).entity(jsonMap).build();
}

private String getExposedErrorDetails(Throwable error) {

StringBuilder buffer = new StringBuilder();
Throwable e = error;
while (e != null) {
if (buffer.length() > 0) {
buffer.append(System.lineSeparator());
}
buffer.append(e.getClass().getSimpleName());
buffer.append(": ");
buffer.append(e.getLocalizedMessage());
e = e.getCause();
}
return buffer.toString();
}

}
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
package com.devonfw.quarkus.productmanagement.domain.repo;

import java.util.Optional;

import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

import com.devonfw.quarkus.productmanagement.domain.model.ProductEntity;

public interface ProductRepository extends CrudRepository<ProductEntity, Long>, ProductFragment {
public interface ProductRepository extends JpaRepository<ProductEntity, Long>, ProductFragment {

@Query("select a from ProductEntity a where title = :title")
ProductEntity findByTitle(@Param("title") String title);
Optional<ProductEntity> findByTitle(@Param("title") String title);

Page<ProductEntity> findAllByOrderByTitle();
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,18 @@

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import javax.ws.rs.NotFoundException;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import com.devonfw.quarkus.general.service.exception.InvalidParameterException;
import com.devonfw.quarkus.productmanagement.domain.model.ProductEntity;
import com.devonfw.quarkus.productmanagement.domain.repo.ProductRepository;
import com.devonfw.quarkus.productmanagement.service.v1.mapper.ProductMapper;
Expand All @@ -24,15 +27,15 @@
@Slf4j
public class UcFindProductImpl implements UcFindProduct {
@Inject
ProductRepository ProductRepository;
ProductRepository productRepository;

@Inject
ProductMapper mapper;

@Override
public Page<ProductDto> findProducts(ProductSearchCriteriaDto dto) {

Iterable<ProductEntity> productsIterator = this.ProductRepository.findAll();
Iterable<ProductEntity> productsIterator = this.productRepository.findAll();
List<ProductEntity> products = new ArrayList<ProductEntity>();
productsIterator.forEach(products::add);
List<ProductDto> productsDto = this.mapper.map(products);
Expand All @@ -42,62 +45,66 @@ public Page<ProductDto> findProducts(ProductSearchCriteriaDto dto) {
@Override
public Page<ProductDto> findProductsByCriteriaApi(ProductSearchCriteriaDto dto) {

List<ProductEntity> products = this.ProductRepository.findAllCriteriaApi(dto).getContent();
List<ProductEntity> products = this.productRepository.findAllCriteriaApi(dto).getContent();
List<ProductDto> productsDto = this.mapper.map(products);
return new PageImpl<>(productsDto, PageRequest.of(dto.getPageNumber(), dto.getPageSize()), productsDto.size());
}

@Override
public Page<ProductDto> findProductsByQueryDsl(ProductSearchCriteriaDto dto) {

List<ProductEntity> products = this.ProductRepository.findAllQueryDsl(dto).getContent();
List<ProductEntity> products = this.productRepository.findAllQueryDsl(dto).getContent();
List<ProductDto> productsDto = this.mapper.map(products);
return new PageImpl<>(productsDto, PageRequest.of(dto.getPageNumber(), dto.getPageSize()), productsDto.size());
}

@Override
public Page<ProductDto> findProductsByTitleQuery(ProductSearchCriteriaDto dto) {

List<ProductEntity> products = this.ProductRepository.findByTitleQuery(dto).getContent();
List<ProductEntity> products = this.productRepository.findByTitleQuery(dto).getContent();
List<ProductDto> productsDto = this.mapper.map(products);
return new PageImpl<>(productsDto, PageRequest.of(dto.getPageNumber(), dto.getPageSize()), productsDto.size());
}

@Override
public Page<ProductDto> findProductsByTitleNativeQuery(ProductSearchCriteriaDto dto) {

List<ProductEntity> products = this.ProductRepository.findByTitleNativeQuery(dto).getContent();
List<ProductEntity> products = this.productRepository.findByTitleNativeQuery(dto).getContent();
List<ProductDto> productsDto = this.mapper.map(products);
return new PageImpl<>(productsDto, PageRequest.of(dto.getPageNumber(), dto.getPageSize()), productsDto.size());
}

@Override
public Page<ProductDto> findProductsOrderedByTitle() {

List<ProductEntity> products = this.ProductRepository.findAllByOrderByTitle().getContent();
List<ProductEntity> products = this.productRepository.findAllByOrderByTitle().getContent();
List<ProductDto> productsDto = this.mapper.map(products);
return new PageImpl<>(productsDto);
}

@Override
public ProductDto findProduct(String id) {

ProductEntity product = this.ProductRepository.findById(Long.valueOf(id)).get();
if (product != null) {
return this.mapper.map(product);
} else {
return null;
try {
Optional<ProductEntity> product = this.productRepository.findById(Long.valueOf(id));
if (product.isPresent()) {
return this.mapper.map(product.get());
} else {
throw new NotFoundException();
}
} catch (NumberFormatException e) {
throw new InvalidParameterException("Unable to parse ID: " + id);
}
}

@Override
public ProductDto findProductByTitle(String title) {

ProductEntity product = this.ProductRepository.findByTitle(title);
if (product != null) {
return this.mapper.map(product);
Optional<ProductEntity> product = this.productRepository.findByTitle(title);
if (product.isPresent()) {
return this.mapper.map(product.get());
} else {
return null;
throw new NotFoundException();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
public interface UcManageProduct {
ProductDto saveProduct(NewProductDto dto);

ProductDto deleteProduct(String id);
void deleteProduct(String id);
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
import javax.inject.Inject;
import javax.inject.Named;
import javax.transaction.Transactional;
import javax.ws.rs.NotFoundException;

import com.devonfw.quarkus.general.service.exception.InvalidParameterException;
import com.devonfw.quarkus.productmanagement.domain.model.ProductEntity;
import com.devonfw.quarkus.productmanagement.domain.repo.ProductRepository;
import com.devonfw.quarkus.productmanagement.service.v1.mapper.ProductMapper;
Expand All @@ -27,14 +29,14 @@ public ProductDto saveProduct(NewProductDto dto) {
}

@Override
public ProductDto deleteProduct(String id) {

ProductEntity product = this.productRepository.findById(Long.valueOf(id)).get();
if (product != null) {
this.productRepository.delete(product);
return this.mapper.map(product);
} else {
return null;
public void deleteProduct(String id) {

try {
this.productRepository.deleteById(Long.valueOf(id));
} catch (NumberFormatException e) {
throw new InvalidParameterException("Unable to parse ID: " + id);
} catch (IllegalArgumentException e) {
throw new NotFoundException();
}
}
}
Loading