This commit is contained in:
Snoweuph 2024-09-04 12:40:01 +02:00
parent 2294ccd30d
commit b4ea8a029a
Signed by: Snoweuph
GPG key ID: 0021ADF278B2F49B
5 changed files with 56 additions and 14 deletions

View file

@ -0,0 +1,14 @@
package de.szut.store.errors;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Date;
@Data
@AllArgsConstructor
public class ErrorDetails {
private Date timestamp;
private String message;
private String details;
}

View file

@ -0,0 +1,26 @@
package de.szut.store.errors;
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.context.request.WebRequest;
import java.util.Date;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorDetails> handleResourceNotFoundException(ResourceNotFoundException exception, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(new Date(), exception.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorDetails> handleException(Exception exception, WebRequest request) {
System.out.println(exception.getMessage());
ErrorDetails errorDetails = new ErrorDetails(new Date(), exception.getMessage(), request.getDescription(false));
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

View file

@ -0,0 +1,9 @@
package de.szut.store.errors;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException{
public ResourceNotFoundException(String message) {super(message);}
}

View file

@ -1,9 +1,11 @@
package de.szut.store.supplier;
import de.szut.store.errors.ResourceNotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class SupplierService {
@ -36,7 +38,11 @@ public class SupplierService {
}
public Supplier readById(Long id) {
return repository.findById(id).orElse(null);
Optional<Supplier> supplier= repository.findById(id);
if (supplier.isEmpty()){
throw new ResourceNotFoundException("Supplier with id " + id + " not found");
}
return supplier.get();
}
public void delete(Long id) {

View file

@ -1,13 +0,0 @@
package de.szut.webshop;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WebshopApplicationTests {
@Test
void contextLoads() {
}
}