add exception handling

This commit is contained in:
mirrerror
2023-11-13 10:11:44 +02:00
parent acbb6285d9
commit 3ba95647b4
10 changed files with 168 additions and 36 deletions

View File

@@ -9,6 +9,10 @@ import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.service.ExpenseCategoryService;
import com.faf223.expensetrackerfaf.service.ExpenseService;
import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotUpdatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -41,7 +45,7 @@ public class ExpenseController {
public ResponseEntity<List<ExpenseDTO>> getAllExpenses() {
List<ExpenseDTO> expenses = expenseService.getTransactions().stream().map(expenseMapper::toDto).collect(Collectors.toList());
if (!expenses.isEmpty()) return ResponseEntity.ok(expenses);
else return ResponseEntity.notFound().build();
else throw new TransactionsNotFoundException("Transactions not found");
}
@PostMapping()
@@ -49,6 +53,9 @@ public class ExpenseController {
BindingResult bindingResult) {
Expense expense = expenseMapper.toExpense(expenseDTO);
if(bindingResult.hasErrors())
throw new TransactionNotCreatedException(ErrorResponse.from(bindingResult).getMessage());
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
@@ -61,7 +68,7 @@ public class ExpenseController {
return ResponseEntity.status(HttpStatus.CREATED).build();
}
return ResponseEntity.notFound().build();
throw new TransactionNotCreatedException("Could not create new expense");
}
@@ -70,6 +77,9 @@ public class ExpenseController {
public ResponseEntity<Void> updateExpense(@PathVariable long id, @RequestBody ExpenseCreationDTO expenseDTO,
BindingResult bindingResult) {
Expense expense = expenseService.getTransactionById(id);
if(expense == null) throw new TransactionsNotFoundException("The expense has not been found");
ExpenseCategory category = expenseCategoryService.getCategoryById(expenseDTO.getExpenseCategory());
expense.setCategory(category);
expense.setAmount(expenseDTO.getAmount());
@@ -78,7 +88,7 @@ public class ExpenseController {
expenseService.createOrUpdate(expense);
return ResponseEntity.status(HttpStatus.CREATED).build();
} else {
return ResponseEntity.notFound().build();
throw new TransactionNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
}
}
@@ -104,14 +114,14 @@ public class ExpenseController {
}
}
return ResponseEntity.notFound().build();
throw new TransactionsNotFoundException("The expenses have not been found");
}
@GetMapping("/categories")
public ResponseEntity<List<ExpenseCategory>> getAllCategories() {
List<ExpenseCategory> categories = expenseCategoryService.getAllCategories();
if (!categories.isEmpty()) return ResponseEntity.ok(categories);
else return ResponseEntity.notFound().build();
else throw new TransactionsNotFoundException("The expenses have not been found");
}
@DeleteMapping("/delete/{id}")

View File

@@ -0,0 +1,56 @@
package com.faf223.expensetrackerfaf.controller;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionDoesNotBelongToTheUserException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleDoesNotBelongException(TransactionDoesNotBelongToTheUserException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleTransactionNotCreatedException(TransactionNotCreatedException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleTransactionsNotFoundException(TransactionsNotFoundException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
@ExceptionHandler
private ResponseEntity<ErrorResponse> handleUserNotFoundException(UserNotFoundException e) {
ErrorResponse response = new ErrorResponse(
e.getMessage(),
System.currentTimeMillis()
);
return new ResponseEntity<>(response, HttpStatus.NOT_FOUND);
}
}

View File

@@ -1,13 +1,18 @@
package com.faf223.expensetrackerfaf.controller;
import com.faf223.expensetrackerfaf.dto.ExpenseDTO;
import com.faf223.expensetrackerfaf.dto.IncomeCreationDTO;
import com.faf223.expensetrackerfaf.dto.IncomeDTO;
import com.faf223.expensetrackerfaf.dto.mappers.IncomeMapper;
import com.faf223.expensetrackerfaf.model.*;
import com.faf223.expensetrackerfaf.model.Income;
import com.faf223.expensetrackerfaf.model.IncomeCategory;
import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.service.IncomeCategoryService;
import com.faf223.expensetrackerfaf.service.IncomeService;
import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.errors.ErrorResponse;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotCreatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionNotUpdatedException;
import com.faf223.expensetrackerfaf.util.exceptions.TransactionsNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@@ -40,13 +45,17 @@ public class IncomeController {
public ResponseEntity<List<IncomeDTO>> getAllIncomes() {
List<IncomeDTO> incomes = incomeService.getTransactions().stream().map(incomeMapper::toDto).collect(Collectors.toList());
if (!incomes.isEmpty()) return ResponseEntity.ok(incomes);
else return ResponseEntity.notFound().build();
else throw new TransactionsNotFoundException("Transactions not found");
}
@PostMapping()
public ResponseEntity<Void> createNewIncome(@RequestBody IncomeCreationDTO incomeDTO,
BindingResult bindingResult) {
Income income = incomeMapper.toIncome(incomeDTO);
if(bindingResult.hasErrors())
throw new TransactionNotCreatedException(ErrorResponse.from(bindingResult).getMessage());
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
@@ -55,12 +64,11 @@ public class IncomeController {
User user = userService.getUserByEmail(email);
income.setUser(user);
System.out.println(income);
incomeService.createOrUpdate(income);
return ResponseEntity.status(HttpStatus.CREATED).build();
}
return ResponseEntity.notFound().build();
throw new TransactionNotCreatedException("Could not create new expense");
}
// TODO: check if the income belongs to the user, extract logic into service
@@ -68,6 +76,9 @@ public class IncomeController {
public ResponseEntity<Void> updateIncome(@PathVariable long id, @RequestBody IncomeCreationDTO incomeDTO,
BindingResult bindingResult) {
Income income = incomeService.getTransactionById(id);
if(income == null) throw new TransactionsNotFoundException("The income has not been found");
IncomeCategory category = incomeCategoryService.getCategoryById(incomeDTO.getIncomeCategory());
income.setCategory(category);
income.setAmount(incomeDTO.getAmount());
@@ -76,30 +87,10 @@ public class IncomeController {
incomeService.createOrUpdate(income);
return ResponseEntity.status(HttpStatus.CREATED).build();
} else {
return ResponseEntity.notFound().build();
throw new TransactionNotUpdatedException(ErrorResponse.from(bindingResult).getMessage());
}
}
@GetMapping("/personal-incomes")
public ResponseEntity<List<IncomeDTO>> getIncomesByUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
String email = userDetails.getUsername();
List<IncomeDTO> incomes = incomeService.getTransactionsByEmail(email).stream().map(incomeMapper::toDto).collect(Collectors.toList());
if (!incomes.isEmpty()) {
return ResponseEntity.ok(incomes);
} else {
return ResponseEntity.ok(Collections.emptyList());
}
}
return ResponseEntity.notFound().build();
}
@GetMapping("/personal-incomes")
public ResponseEntity<List<IncomeDTO>> getExpensesByUser(@RequestParam Optional<LocalDate> date,
@RequestParam Optional<Month> month) {
@@ -122,14 +113,14 @@ public class IncomeController {
}
}
return ResponseEntity.notFound().build();
throw new TransactionsNotFoundException("The expenses have not been found");
}
@GetMapping("/categories")
public ResponseEntity<List<IncomeCategory>> getAllCategories() {
List<IncomeCategory> categories = incomeCategoryService.getAllCategories();
if (!categories.isEmpty()) return ResponseEntity.ok(categories);
else return ResponseEntity.notFound().build();
else throw new TransactionsNotFoundException("The expenses have not been found");
}
@DeleteMapping("/delete/{id}")

View File

@@ -5,6 +5,7 @@ import com.faf223.expensetrackerfaf.dto.UserDTO;
import com.faf223.expensetrackerfaf.dto.mappers.UserMapper;
import com.faf223.expensetrackerfaf.model.User;
import com.faf223.expensetrackerfaf.service.UserService;
import com.faf223.expensetrackerfaf.util.exceptions.UserNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
@@ -32,7 +33,7 @@ public class UserController {
userService.updateUser(user);
return ResponseEntity.ok(userMapper.toDto(user));
} else {
return ResponseEntity.notFound().build();
throw new UserNotFoundException("The user has not been found");
}
}
@@ -43,9 +44,8 @@ public class UserController {
if (authentication != null && authentication.getPrincipal() instanceof UserDetails userDetails) {
User user = userService.getUserByEmail(userDetails.getUsername());
if (user != null) return ResponseEntity.ok(userMapper.toDto(user));
else return ResponseEntity.notFound().build();
}
return ResponseEntity.notFound().build();
throw new UserNotFoundException("The user has not been found");
}
@GetMapping()

View File

@@ -0,0 +1,40 @@
package com.faf223.expensetrackerfaf.util.errors;
import lombok.Data;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import java.util.List;
@Data
public class ErrorResponse {
private String message;
private long timestamp;
public ErrorResponse(String message, long timestamp) {
this.message = message;
this.timestamp = timestamp;
}
public ErrorResponse(String message) {
this.message = message;
this.timestamp = System.currentTimeMillis();
}
public static ErrorResponse from(BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
StringBuilder errorMessage = new StringBuilder();
List<FieldError> errors = bindingResult.getFieldErrors();
for(FieldError fieldError : errors)
errorMessage.append(fieldError.getField())
.append(" - ")
.append(fieldError.getDefaultMessage())
.append(";");
return new ErrorResponse(errorMessage.toString(), System.currentTimeMillis());
}
return new ErrorResponse("No error message was provided", System.currentTimeMillis());
}
}

View File

@@ -0,0 +1,7 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class TransactionDoesNotBelongToTheUserException extends RuntimeException {
public TransactionDoesNotBelongToTheUserException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,7 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class TransactionNotCreatedException extends RuntimeException {
public TransactionNotCreatedException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,7 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class TransactionNotUpdatedException extends RuntimeException {
public TransactionNotUpdatedException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,7 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class TransactionsNotFoundException extends RuntimeException {
public TransactionsNotFoundException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,7 @@
package com.faf223.expensetrackerfaf.util.exceptions;
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}