1
package by.andd3dfx.templateapp.error;
3
import by.andd3dfx.templateapp.error.exception.NotFoundException;
4
import by.andd3dfx.templateapp.error.exception.UnauthorizedException;
5
import by.andd3dfx.templateapp.error.dto.ExceptionResponse;
6
import org.springframework.http.HttpStatus;
7
import org.springframework.http.ResponseEntity;
8
import org.springframework.web.bind.annotation.ControllerAdvice;
9
import org.springframework.web.bind.annotation.ExceptionHandler;
10
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
12
import java.time.LocalDateTime;
15
* Add more methods if needed.
18
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
23
@ExceptionHandler(UnauthorizedException.class)
24
public ResponseEntity<ExceptionResponse> handleUnauthorizedException(UnauthorizedException ex) {
25
return buildResponseEntity(ex, HttpStatus.UNAUTHORIZED);
31
@ExceptionHandler(NotFoundException.class)
32
public ResponseEntity handleResourceNotFoundException(NotFoundException ex) {
33
return buildResponseEntity(ex, HttpStatus.NOT_FOUND);
39
@ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
40
public ResponseEntity handleIllegalExceptions(RuntimeException ex) {
41
return buildResponseEntity(ex, HttpStatus.CONFLICT);
46
* Throw exception for any other unpredicted reason.
47
* Avoid modification of this method to make problem visible in logs.
48
* Don't delete this method to avoid descendants declare it and catch 'any error'.
50
@ExceptionHandler(Exception.class)
51
public final ResponseEntity handleOtherExceptions(Exception ex) throws Exception {
55
private ResponseEntity<ExceptionResponse> buildResponseEntity(Exception ex, HttpStatus httpStatus) {
58
.body(new ExceptionResponse(ex.getMessage(), httpStatus.name(), LocalDateTime.now()));