Skip to content

Commit 72f9e3b

Browse files
committed
feat: add ErrorResponseDTO.java
1 parent 9f6d0dd commit 72f9e3b

2 files changed

Lines changed: 51 additions & 3 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package com.example.SorokinSpringBoot;
2+
3+
import java.time.LocalDateTime;
4+
5+
public record ErrorResponseDTO(String message,
6+
String detailedMessage,
7+
LocalDateTime errorTime) {
8+
9+
10+
11+
}
Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
package com.example.SorokinSpringBoot.exceptions;
22

3+
import com.example.SorokinSpringBoot.ErrorResponseDTO;
4+
import jakarta.persistence.EntityNotFoundException;
5+
import org.springframework.http.HttpStatus;
36
import org.springframework.http.ResponseEntity;
47
import org.springframework.web.bind.annotation.ControllerAdvice;
58
import org.springframework.web.bind.annotation.ExceptionHandler;
69

10+
import java.time.LocalDateTime;
711
import java.util.logging.Logger;
812

913
@ControllerAdvice
@@ -12,9 +16,42 @@ public class GlobalExceptionHandler {
1216
private static final Logger logger = Logger.getLogger(GlobalExceptionHandler.class.getName());
1317

1418
@ExceptionHandler(Exception.class)
15-
public ResponseEntity<Void> handleGenericException(Exception exception) {
16-
logger.warning("Handle exception" + exception);
17-
return ResponseEntity.status(500).build();
19+
public ResponseEntity<ErrorResponseDTO> handleGenericException(Exception exception) {
20+
logger.warning("Handle exception " + exception);
21+
22+
var errorDTO = new ErrorResponseDTO(
23+
"Internal server error",
24+
exception.getMessage(),
25+
LocalDateTime.now()
26+
);
27+
28+
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorDTO);
29+
}
30+
31+
@ExceptionHandler(EntityNotFoundException.class)
32+
public ResponseEntity<ErrorResponseDTO> handleEntityNotFound(Exception exception) {
33+
logger.warning("Handle EntityNotFound " + exception.getMessage());
34+
35+
var errorDTO = new ErrorResponseDTO(
36+
"Entity not found error",
37+
exception.getMessage(),
38+
LocalDateTime.now()
39+
);
40+
41+
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorDTO);
42+
}
43+
44+
@ExceptionHandler(exception = {IllegalArgumentException.class, IllegalStateException.class})
45+
public ResponseEntity<ErrorResponseDTO> handleIllegalArgumentException(Exception exception) {
46+
logger.warning("Handle exception " + exception);
47+
48+
var errorDTO = new ErrorResponseDTO(
49+
"Entity not found error",
50+
exception.getMessage(),
51+
LocalDateTime.now()
52+
);
53+
54+
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorDTO);
1855
}
1956

2057
}

0 commit comments

Comments
 (0)