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

Implement error-pages #7

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-22041afd0340ce965d47ae6ef1cefeee28c7c493a6346c4f15d667ab976d596c.svg)](https://classroom.github.com/a/fcC7yEpn)
# Java Online Marathon
## To-Do List Project
1. Implement exception handling for custom exception.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.softserve.itacademy.controller;

import com.softserve.itacademy.exception.EntityNotFoundException;
import com.softserve.itacademy.exception.NullEntityReferenceException;
import com.softserve.itacademy.model.User;
import com.softserve.itacademy.service.RoleService;
import com.softserve.itacademy.service.UserService;
Expand All @@ -9,6 +11,8 @@
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.AttributedString;

@Controller
@RequestMapping("/users")
public class UserController {
Expand All @@ -24,40 +28,106 @@ public UserController(UserService userService, RoleService roleService) {
@GetMapping("/create")
public String create(Model model) {
model.addAttribute("user", new User());
model.addAttribute("roles", roleService.getAll());
return "create-user";
}

@PostMapping("/create")
public String create(@Validated @ModelAttribute("user") User user, BindingResult result) {
public String create(@Validated @ModelAttribute("user") User user, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("roles", roleService.getAll());
return "create-user";
}
// throw new RuntimeException("Testing 500 Internal Server Error");
try {

user.setPassword(user.getPassword());
user.setRole(roleService.readById(2));

User newUser = userService.create(user);
return "redirect:/todos/all/users/" + newUser.getId();
} catch (NullEntityReferenceException e) {
model.addAttribute("errorMessage", e.getMessage());
model.addAttribute("roles", roleService.getAll());
return "create-user";
} catch (Exception e) {
model.addAttribute("errorMessage", e.getMessage());
return "create-user";
}
}

@GetMapping("/{id}/read")
public String read(@PathVariable long id, Model model) {
User user = userService.readById(id);
model.addAttribute("user", user);
return "user-info";
try {

User user = userService.readById(id);
model.addAttribute("user", user);
return "user-info";
} catch (EntityNotFoundException e) {
model.addAttribute("errorMessage", e.getMessage());
return "404-page";
} catch (Exception e) {
model.addAttribute("errorMessage", e.getMessage());
return "500-page";
}
}

@GetMapping("/{id}/update")
public String update(@PathVariable long id, Model model) {
try {


User user = userService.readById(id);
model.addAttribute("user", user);
model.addAttribute("roles", roleService.getAll());
return "update-user";
} catch (EntityNotFoundException e) {
model.addAttribute("errorMessage", e.getMessage());
return "404-page";
} catch (Exception e) {
model.addAttribute("errorMessage", e.getMessage());
return "500-page";
}
}

@PostMapping("/{id}/update")
public String update(@Validated @ModelAttribute("user") User user, BindingResult result, Model model) {
if (result.hasErrors()) {
model.addAttribute("roles", roleService.getAll());
return "update-user";
}

try {
user.setRole(roleService.readById(user.getRole().getId()));
userService.update(user);
return "redirect:/users/" + user.getId() + "/read";
} catch (NullEntityReferenceException e) {
model.addAttribute("errorMessage", e.getMessage());
model.addAttribute("roles", roleService.getAll());
return "update-user";
} catch (EntityNotFoundException e) {
model.addAttribute("errorMessage", e.getMessage());
return "404-page";
} catch (Exception e) {
model.addAttribute("errorMessage", e.getMessage());
return "500-page";
}
}


@GetMapping("/{id}/delete")
public String delete(@PathVariable("id") long id) {
public String delete(@PathVariable("id") long id, Model model) {
try {

userService.delete(id);
return "redirect:/users/all";
} catch (EntityNotFoundException e) {
model.addAttribute("errorMessage", e.getMessage());
return "404-page";
} catch (Exception e) {
model.addAttribute("errorMessage", e.getMessage());
return "500-page";
}
}

@GetMapping("/all")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.softserve.itacademy.exception;

public class EntityNotFoundException extends RuntimeException {
public EntityNotFoundException(String message) {
super(message);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.softserve.itacademy.exception;

import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleNoHandlerFoundException(NoHandlerFoundException ex, Model model) {
model.addAttribute("errorMessage", "Page not found");
return "404-page";
}
@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleEntityNotFoundException(EntityNotFoundException ex, Model model) {
model.addAttribute("errorMessage", ex.getMessage());
return "404-page";
}


@ExceptionHandler(NullEntityReferenceException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleNullEntityReferenceException(NullEntityReferenceException ex, Model model) {
model.addAttribute("errorMessage", ex.getMessage());
return "400-page";
}

@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleGenericException(Exception ex, Model model) {
model.addAttribute("errorMessage", ex.getMessage());
return "500-page";
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.softserve.itacademy.exception;

public class NullEntityReferenceException extends RuntimeException {
public NullEntityReferenceException(String message) {
super(message);
}

}
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.softserve.itacademy.service.impl;

import com.softserve.itacademy.exception.EntityNotFoundException;
import com.softserve.itacademy.exception.NullEntityReferenceException;
import com.softserve.itacademy.model.Role;
import com.softserve.itacademy.repository.RoleRepository;
import com.softserve.itacademy.service.RoleService;
Expand All @@ -20,27 +22,40 @@ public RoleServiceImpl(RoleRepository roleRepository) {

@Override
public Role create(Role role) {
return roleRepository.save(role);
if (role == null) {
throw new NullEntityReferenceException("Role cannot be null");
}

return roleRepository.save(role);
}

@Override
public Role readById(long id) {
Optional<Role> optional = roleRepository.findById(id);
return optional.get();
if (optional.isEmpty()) {
throw new EntityNotFoundException("Role with id " + id + " not found");
}
return optional.get();
}

@Override
public Role update(Role role) {
Role oldRole = readById(role.getId());
return roleRepository.save(role);
if (role == null) {
throw new NullEntityReferenceException("Role cannot be null");
}
if (!roleRepository.existsById(role.getId())) {
throw new EntityNotFoundException("Role with id " + role.getId() + " not found");
}
return roleRepository.save(role);
}

@Override
public void delete(long id) {
Role role = readById(id);
roleRepository.delete(role);
if (!roleRepository.existsById(id)) {
throw new EntityNotFoundException("Role with id " + id + " not found");
}
roleRepository.deleteById(id);
}

@Override
public List<Role> getAll() {
List<Role> roles = roleRepository.findAll();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.softserve.itacademy.service.impl;

import com.softserve.itacademy.exception.EntityNotFoundException;
import com.softserve.itacademy.exception.NullEntityReferenceException;
import com.softserve.itacademy.model.State;
import com.softserve.itacademy.repository.StateRepository;
import com.softserve.itacademy.service.StateService;
Expand All @@ -19,33 +21,52 @@ public StateServiceImpl(StateRepository stateRepository) {

@Override
public State create(State state) {
return stateRepository.save(state);
if (state == null) {
throw new NullEntityReferenceException("State cannot be null");
}

return stateRepository.save(state);
}

@Override
public State readById(long id) {
Optional<State> optional = stateRepository.findById(id);
return optional.get();
if (optional.isEmpty()) {
throw new EntityNotFoundException("State with id " + id + " not found");
}
return optional.get();
}

@Override
public State update(State state) {
State oldState = readById(state.getId());
if (state == null) {
throw new NullEntityReferenceException("State cannot be null");
}
if (!stateRepository.existsById(state.getId())) {
throw new EntityNotFoundException("State with id " + state.getId() + " not found");
}
return stateRepository.save(state);
}

@Override
public void delete(long id) {
State state = readById(id);
stateRepository.delete(state);
if (!stateRepository.existsById(id)) {
throw new EntityNotFoundException("State with id " + id + " not found");
}
stateRepository.deleteById(id);
}


@Override
public State getByName(String name) {
Optional<State> optional = Optional.ofNullable(stateRepository.getByName(name));
return optional.get();
if (optional.isEmpty()) {
throw new EntityNotFoundException("State with name " + name + " not found");
}
return optional.get();
}


@Override
public List<State> getAll() {
List<State> states = stateRepository.getAll();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.softserve.itacademy.service.impl;

import com.softserve.itacademy.exception.EntityNotFoundException;
import com.softserve.itacademy.exception.NullEntityReferenceException;
import com.softserve.itacademy.model.Task;
import com.softserve.itacademy.repository.TaskRepository;
import com.softserve.itacademy.service.TaskService;
Expand All @@ -18,26 +20,39 @@ public TaskServiceImpl(TaskRepository taskRepository) {
}

@Override
public Task create(Task user) {
return taskRepository.save(user);
public Task create(Task task) {
if (task == null) {
throw new NullEntityReferenceException("Task cannot be null");
}
return taskRepository.save(task);
}

@Override
public Task readById(long id) {
Optional<Task> optional = taskRepository.findById(id);
return optional.get();
if (optional.isEmpty()) {
throw new EntityNotFoundException("Task with id " + id + " not found");
}
return optional.get();
}

@Override
public Task update(Task task) {
Task oldTask = readById(task.getId());
return taskRepository.save(task);
if (task == null) {
throw new NullEntityReferenceException("Task cannot be null");
}
if (!taskRepository.existsById(task.getId())) {
throw new EntityNotFoundException("Task with id " + task.getId() + " not found");
}
return taskRepository.save(task);
}

@Override
public void delete(long id) {
Task task = readById(id);
taskRepository.delete(task);
if (!taskRepository.existsById(id)) {
throw new EntityNotFoundException("Task with id " + id + " not found");
}
taskRepository.deleteById(id);
}

@Override
Expand All @@ -46,6 +61,7 @@ public List<Task> getAll() {
return tasks.isEmpty() ? new ArrayList<>() : tasks;
}


@Override
public List<Task> getByTodoId(long todoId) {
List<Task> tasks = taskRepository.getByTodoId(todoId);
Expand Down
Loading