Java for Beginner
710 subscribers
618 photos
166 videos
12 files
967 links
Канал от новичков для новичков!
Изучайте Java вместе с нами!
Здесь мы обмениваемся опытом и постоянно изучаем что-то новое!

Наш YouTube канал - https://www.youtube.com/@Java_Beginner-Dev

Наш канал на RUTube - https://rutube.ru/channel/37896292/
Download Telegram
5. Использование встроенного механизма Spring Boot для ошибок

Spring Boot предоставляет удобный способ настройки кастомных страниц через файл application.properties:
server.error.whitelabel.enabled=false
server.error.path=/error


Затем создаем контроллер для обработки пути /error:
@Controller
public class CustomErrorController {

@GetMapping("/error")
public String handleError() {
return "error/custom";
}
}


Добавляем страницу src/main/resources/templates/error/custom.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Error</title>
</head>
<body>
<h1>An error occurred</h1>
<p>We are sorry, something went wrong.</p>
</body>
</html>


6. Обработка JSON-ответов для API

Для REST API ошибки обычно возвращаются в формате JSON. Пример глобального обработчика для API:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

@ControllerAdvice
public class ApiErrorController {

@ExceptionHandler(AccessDeniedException.class)
public ResponseEntity<?> handleAccessDeniedException(AccessDeniedException ex) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body(Map.of(
"error", "Forbidden",
"message", ex.getMessage()
));
}
@ExceptionHandler(AuthenticationException.class)
public ResponseEntity<?> handleAuthenticationException(AuthenticationException ex) {
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Map.of(
"error", "Unauthorized",
"message", ex.getMessage()
));
}
}


#Java #Training #Spring #Security #Security_Exceptions
👍1