Skip to content

Commit 2d0095d

Browse files
committed
ExceptionHandler
1 parent 906c4b7 commit 2d0095d

File tree

7 files changed

+107
-54
lines changed

7 files changed

+107
-54
lines changed

src/main/java/com/itacademy/CrudEmpleats/controller/ControllerEmployees.java

Lines changed: 8 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,30 +6,18 @@
66
import javax.servlet.http.HttpServletResponse;
77

88
import org.springframework.beans.factory.annotation.Autowired;
9+
import org.springframework.http.HttpStatus;
910
import org.springframework.web.bind.annotation.*;
1011

1112
import com.itacademy.CrudEmpleats.domain.Employee;
1213
import com.itacademy.CrudEmpleats.persistence.EmployeeRepository;
1314

1415
@RestController
1516
public class ControllerEmployees {
16-
1717
/*
18-
* Crearem un programa de gestió d'empleats molt senzill on depenent de la feina
19-
* de l'empleat se li assignarà un salari automàticament
20-
*
21-
* El domini ha de tindre el CRUD al complet (Create, Read, Update, Delete),
22-
* utilitzant els verbs HTTP associats.
23-
*
24-
* Crea una petició HTTP especial que busqui empleats per feina, a més de totes
25-
* les que creen, llegeixen, actualitzen o esborren elements de tipus empleat
26-
*
27-
* Has de tindre en compte les bones pràctiques de disseny de les API: utilitzi
28-
* correctament els codis d'error i les respostes en cas d'invocacions
29-
* incorrectes
30-
*
18+
* Controlador d'operacions CRUD
3119
*/
32-
20+
3321
@Autowired
3422
private EmployeeRepository repositori;
3523

@@ -42,6 +30,7 @@ void start(HttpServletResponse reponse) throws IOException {
4230

4331
// Crear nou empleat
4432
@PostMapping( "/Empleat")
33+
@ResponseStatus(HttpStatus.CREATED) // 201
4534
public Employee addEmployee(@RequestBody Employee employee) {
4635
repositori.addEmployee(employee);
4736
return employee;
@@ -61,18 +50,17 @@ public Employee getFirstEmployee(@PathVariable("id") int id) {
6150

6251
// Actualitzar Empleat
6352
@PutMapping("/Empleat/{id}")
53+
@ResponseStatus(HttpStatus.ACCEPTED) // 202
6454
public Employee updateEmployee(@RequestBody Employee employee, @PathVariable("id") int id) {
6555
repositori.updateEmployee(employee,id);
6656
return repositori.getEmployeeById(id);
6757
}
6858

6959
// Eliminar Empleat
7060
@DeleteMapping("/Empleat/{id}")
71-
public String deleteEmployee( @PathVariable("id") int id) {
72-
repositori.deleteEmployee(id);
73-
if(repositori.getEmployeeById(id)==null) {
61+
@ResponseStatus(HttpStatus.ACCEPTED) // 202
62+
public String deleteEmployee(@PathVariable("id") int id) {
63+
repositori.deleteEmployee(id);
7464
return "Empleat eliminat correctament.";
75-
}
76-
return "L'emplat no s'ha pogut eliminar.";
7765
}
7866
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.itacademy.CrudEmpleats.controller;
2+
3+
import org.springframework.http.HttpStatus;
4+
5+
import org.springframework.web.bind.annotation.ExceptionHandler;
6+
import org.springframework.web.bind.annotation.ResponseStatus;
7+
import org.springframework.web.bind.annotation.RestControllerAdvice;
8+
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
9+
10+
import com.itacademy.CrudEmpleats.exceptions.IdNotFound;
11+
12+
@RestControllerAdvice
13+
public class ControllerExceptions {
14+
15+
//Excepció si no s'indrodueix un integer al id de la petició.
16+
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
17+
@ResponseStatus(HttpStatus.PRECONDITION_FAILED) // 412
18+
public String misMatchException(MethodArgumentTypeMismatchException e) {
19+
return "<h2>Error!</h2>"
20+
+ "El paràmetre <strong>" + e.getName()+" = " + e.getValue() + "</strong>"
21+
+ " ha de ser del tipus <strong>"+ e.getRequiredType() + "</strong>.";
22+
}
23+
24+
//Excepció is no es troba l'element demanat.
25+
@ExceptionHandler(IdNotFound.class)
26+
@ResponseStatus(HttpStatus.NOT_FOUND) // 404
27+
public String noSuchElementException(IdNotFound e) {
28+
return "<h2>Error!</h2>"
29+
+ "No s'ha trobat cap empleat amb el ID: " + e.getId();
30+
}
31+
32+
33+
//Filtre per errors no controlats amb informació per millorar l'aplicació.
34+
@ExceptionHandler(Exception.class)
35+
@ResponseStatus(HttpStatus.CONFLICT) // 409
36+
public String exceptionHandeler(Exception e) {
37+
return "<h2>Error!</h2>"
38+
+ "Tipo: " + e.getClass() + "<br>"
39+
+ "Mensaje Error: " + e.getMessage();
40+
}
41+
}

src/main/java/com/itacademy/CrudEmpleats/domain/Employee.java

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,24 +2,14 @@
22

33
public class Employee {
44

5-
/*
6-
* D'un treballador identifiquem el nom i la seva feina, estaria bé tenir un
7-
* identificador únic per aquest treballador.
8-
* Depenent de la feina s'assignarà un
9-
* salari a l'empleat un cop es crea.
10-
*
11-
*/
12-
13-
private static int idCount=0;
145
private int id;
156
private String name;
167
private String job;
178
private double salary ;
189

19-
20-
21-
public Employee(String name, String job) {
22-
this.id=idCount++;
10+
//salari i cárreg en funció de la calsse Jobs Enum.
11+
public Employee(int id,String name, String job) {
12+
this.id=id;
2313
this.name = name;
2414
this.job = Jobs.valueOf(job).getName();
2515
this.salary = Jobs.valueOf(job).getSalary();
@@ -48,7 +38,5 @@ public void setJob(String job) {
4838
public double getSalary() {
4939
return salary;
5040
}
51-
52-
53-
41+
5442
}

src/main/java/com/itacademy/CrudEmpleats/domain/Jobs.java

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,7 @@
22

33
public enum Jobs {
44

5-
/*
6-
* Les feines són fixes, és a dir ja estan definits en un ENUMERABLE.
7-
*
8-
*/
5+
//Enum que defineix nom del carreg i sou.
96

107
Director_Projectes("Director de projectes",50000),
118
Programador_Senior("Programador Senior",35000),
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package com.itacademy.CrudEmpleats.exceptions;
2+
3+
public class IdNotFound extends RuntimeException {
4+
5+
private int id;
6+
7+
public IdNotFound(int id) {
8+
this.id=id;
9+
}
10+
11+
public int getId() {
12+
return id;
13+
}
14+
}

src/main/java/com/itacademy/CrudEmpleats/persistence/EmployeeRepository.java

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,31 @@
55
import org.springframework.stereotype.Service;
66

77
import com.itacademy.CrudEmpleats.domain.Employee;
8+
import com.itacademy.CrudEmpleats.exceptions.IdNotFound;
89

910
@Service
10-
public class EmployeeRepository {
11+
public class EmployeeRepository implements IEmployeeRepository{
1112

12-
/*
13-
* Els objectes seran persistits únicament en memòria
14-
*
15-
*/
13+
// Els objectes persistents únicament en memòria
1614

15+
private static int idcount=0;
16+
/*
1717
private List<Employee> repository = new ArrayList<>(
1818
Arrays.asList(
1919
new Employee("Joan", "Director_Projectes"),
2020
new Employee("Gerard", "Programador_Junior"),
2121
new Employee("Maria", "Administrativa")
2222
)
2323
);
24+
*/
25+
private List<Employee> repository = new ArrayList<>(
26+
Arrays.asList(
27+
new Employee(idcount++,"Joan", "Director_Projectes"),
28+
new Employee(idcount++,"Gerard", "Programador_Junior"),
29+
new Employee(idcount++,"Maria", "Administrativa")
30+
)
31+
);
32+
2433

2534
public List<Employee> getAllEmployees() {
2635
return repository;
@@ -30,26 +39,23 @@ public Employee getEmployeeById(int id){
3039
try {
3140
return repository.stream().filter(employee -> employee.getId()==id).findFirst().get();
3241
} catch (Exception e) {
33-
return null;
42+
throw new IdNotFound(id);
3443
}
35-
3644
}
3745

3846
public void addEmployee(Employee employee) {
47+
employee.setId(idcount++);
3948
repository.add(employee);
40-
4149
}
4250

4351
public void updateEmployee(Employee employee, int id) {
44-
for(Employee e : repository) {
45-
if(e.getId()==id) {
46-
repository.set(repository.indexOf(e),employee);
47-
}
48-
}
52+
Employee existingEmployee = getEmployeeById(id);
53+
employee.setId(id); //garantitzar que el nou objecte tingui el mateix id que l'antic.
54+
repository.set(repository.indexOf(existingEmployee),employee);
4955
}
5056

5157
public void deleteEmployee(int id) {
52-
repository.removeIf(empleat -> empleat.getId()==id);
58+
repository.remove(getEmployeeById(id));
5359
}
5460

5561
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
package com.itacademy.CrudEmpleats.persistence;
2+
3+
import java.util.List;
4+
5+
import com.itacademy.CrudEmpleats.domain.Employee;
6+
7+
public interface IEmployeeRepository {
8+
9+
public List<Employee> getAllEmployees();
10+
11+
public Employee getEmployeeById(int id);
12+
13+
public void addEmployee(Employee employee);
14+
15+
public void updateEmployee(Employee employee, int id);
16+
17+
public void deleteEmployee(int id);
18+
19+
}

0 commit comments

Comments
 (0)