Skip to content

Commit

Permalink
feat: add error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
OskarWiedeweg committed Dec 12, 2023
1 parent 4f08315 commit e39e8ab
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.oskarwiedeweg.cloudwork.error;

import com.oskarwiedeweg.cloudwork.error.dto.ErrorDto;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.ErrorResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import java.time.LocalDateTime;

@ControllerAdvice
public class GlobalErrorHandler {

@ExceptionHandler(Throwable.class)
public ResponseEntity<ErrorDto> handleError(Throwable throwable) {
if (!(throwable instanceof ErrorResponse errorResponse)) {
return construct(HttpStatus.INTERNAL_SERVER_ERROR, HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
}
return construct(errorResponse.getStatusCode(),
HttpStatus.resolve(errorResponse.getStatusCode().value()).getReasonPhrase());
}

@ExceptionHandler(ResponseStatusException.class)
public ResponseEntity<ErrorDto> handleError(ResponseStatusException throwable) {
return construct(throwable.getStatusCode(), throwable.getMessage());
}


private ResponseEntity<ErrorDto> construct(HttpStatusCode statusCode, Object error) {
return ResponseEntity.status(statusCode).body(new ErrorDto(
statusCode.value(),
ServletUriComponentsBuilder.fromCurrentRequest()
.build()
.getPath(),
error,
LocalDateTime.now()
));
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.oskarwiedeweg.cloudwork.error.dto;

import java.time.LocalDateTime;

public record ErrorDto(int status, String path, Object error, LocalDateTime timestamp) {
}

0 comments on commit e39e8ab

Please sign in to comment.