Skip to content

Commit

Permalink
feat: Added custom Error
Browse files Browse the repository at this point in the history
  • Loading branch information
miguel-merlin committed Apr 8, 2024
1 parent fb4a272 commit a262164
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.sitblueprint.admin.controller.exceptions;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@AllArgsConstructor
@NoArgsConstructor
public class ApiError {
private LocalDateTime timestamp;
private int status;
private String error;
private String message;
private String path;
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,29 @@
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;

import java.time.LocalDateTime;
import java.util.NoSuchElementException;

@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ServiceException.class)
public ResponseEntity<String> handleServiceException(ServiceException e, WebRequest request) {
return new ResponseEntity<>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
public ResponseEntity<ApiError> handleServiceException(ServiceException e, WebRequest request) {
ApiError apiError = new ApiError(LocalDateTime.now(), HttpStatus.INTERNAL_SERVER_ERROR.value(),
"Internal Server Error", e.getMessage(), request.getDescription(false));
return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
}

@ExceptionHandler(NoSuchElementException.class)
public ResponseEntity<String> handleNoSuchElementException(NoSuchElementException e, WebRequest request) {
return new ResponseEntity<>("Resource not found", HttpStatus.NOT_FOUND);
public ResponseEntity<ApiError> handleNoSuchElementException(NoSuchElementException e, WebRequest request) {
ApiError apiError = new ApiError(LocalDateTime.now(), HttpStatus.NOT_FOUND.value(),
"Not Found Error", e.getMessage(), request.getDescription(false));
return new ResponseEntity<>(apiError, HttpStatus.NOT_FOUND);
}

@ExceptionHandler(Exception.class)
public ResponseEntity<String> handleGenericException(Exception e, WebRequest request) {
return new ResponseEntity<String>("An unexpected error has occurred", HttpStatus.INTERNAL_SERVER_ERROR);
public ResponseEntity<ApiError> handleGenericException(Exception e, WebRequest request) {
ApiError apiError = new ApiError(LocalDateTime.now(), HttpStatus.INTERNAL_SERVER_ERROR.value(),
"Internal Server Error", e.getMessage(), request.getDescription(false));
return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

0 comments on commit a262164

Please sign in to comment.