Skip to content

Commit 6307981

Browse files
committed
feat: add abstract exception handler
1 parent 0fb44cd commit 6307981

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
package br.com.catalog.exceptions.abstract_handler;
2+
3+
import com.fasterxml.jackson.annotation.JsonFormat;
4+
import org.slf4j.Logger;
5+
import org.springframework.http.HttpStatus;
6+
import org.springframework.http.ResponseEntity;
7+
import org.springframework.web.bind.annotation.ExceptionHandler;
8+
import org.springframework.web.bind.annotation.ResponseBody;
9+
import org.springframework.web.bind.annotation.ResponseStatus;
10+
11+
import java.time.LocalDateTime;
12+
13+
public abstract class AbstractExceptionHandler {
14+
private final Logger log;
15+
16+
protected AbstractExceptionHandler(Logger log) {
17+
this.log = log;
18+
}
19+
20+
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
21+
@ResponseBody
22+
@ExceptionHandler(Exception.class)
23+
public ResponseEntity<ApiError> handlerGeneric(final Exception ex) {
24+
log.error("UNEXPECTED ERROR", ex);
25+
var apiError = new ApiError(
26+
HttpStatus.INTERNAL_SERVER_ERROR.value(),
27+
HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase(),
28+
"An unexpected internal server error occured");
29+
return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
30+
}
31+
32+
public record ApiError(
33+
@JsonFormat(pattern = "dd-MM-yyyy HH:mm:ss")
34+
LocalDateTime timestamp,
35+
int code,
36+
String status,
37+
String description
38+
) {
39+
public ApiError(int code, String status, String description) {
40+
this(LocalDateTime.now(), code, status, description);
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)