Skip to content

Commit

Permalink
Merge pull request #112 from szymonpoltorak/DEV-194-Exception-handler
Browse files Browse the repository at this point in the history
DEV-194 Added abstract exception handler
  • Loading branch information
szymonpoltorak authored May 7, 2024
2 parents fe8f7db + 4fdb32d commit 1b2cbee
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package dev.corn.cornbackend.utils.exceptions;

import dev.corn.cornbackend.utils.exceptions.data.AbstractExceptionResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;

@RestControllerAdvice
@Slf4j
public class AbstractExceptionHandler {

private static final String EXCEPTION_OCCURRED_MESSAGE = "Exception occurred with status: {} and response: {}";

@ExceptionHandler(AbstractException.class)
public final ResponseEntity<AbstractExceptionResponse> handleAbstractException(AbstractException exception) {
AbstractExceptionResponse response = buildExceptionResponse(exception);

HttpStatus status = HttpStatus.valueOf(exception.getStatusCode().value());

log.error(EXCEPTION_OCCURRED_MESSAGE, status.value(), response);
log.error("", exception);

return ResponseEntity.status(status).body(response);
}

private AbstractExceptionResponse buildExceptionResponse(Exception exception) {
return AbstractExceptionResponse.builder()
.exceptionMessage(exception.getMessage())
.exceptionName(exception.getClass().getSimpleName())
.timeStamp(LocalDateTime.now())
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package dev.corn.cornbackend.utils.exceptions.data;

import lombok.Builder;

import java.time.LocalDateTime;

@Builder
public record AbstractExceptionResponse(String exceptionName, String exceptionMessage, LocalDateTime timeStamp){
}

0 comments on commit 1b2cbee

Please sign in to comment.