composite-build-usage-example

Форк
0
60 строк · 2.1 Кб
1
package by.andd3dfx.templateapp.error;
2

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;
11

12
import java.time.LocalDateTime;
13

14
/**
15
 * Add more methods if needed.
16
 */
17
@ControllerAdvice
18
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
19

20
    /**
21
     * 401.
22
     */
23
    @ExceptionHandler(UnauthorizedException.class)
24
    public ResponseEntity<ExceptionResponse> handleUnauthorizedException(UnauthorizedException ex) {
25
        return buildResponseEntity(ex, HttpStatus.UNAUTHORIZED);
26
    }
27

28
    /**
29
     * 404.
30
     */
31
    @ExceptionHandler(NotFoundException.class)
32
    public ResponseEntity handleResourceNotFoundException(NotFoundException ex) {
33
        return buildResponseEntity(ex, HttpStatus.NOT_FOUND);
34
    }
35

36
    /**
37
     * 409.
38
     */
39
    @ExceptionHandler({IllegalArgumentException.class, IllegalStateException.class})
40
    public ResponseEntity handleIllegalExceptions(RuntimeException ex) {
41
        return buildResponseEntity(ex, HttpStatus.CONFLICT);
42
    }
43

44
    /**
45
     * 500.
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'.
49
     */
50
    @ExceptionHandler(Exception.class)
51
    public final ResponseEntity handleOtherExceptions(Exception ex) throws Exception {
52
        throw ex;
53
    }
54

55
    private ResponseEntity<ExceptionResponse> buildResponseEntity(Exception ex, HttpStatus httpStatus) {
56
        return ResponseEntity
57
                .status(httpStatus)
58
                .body(new ExceptionResponse(ex.getMessage(), httpStatus.name(), LocalDateTime.now()));
59
    }
60
}
61

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.