Skip to content

Commit

Permalink
Add locale to exception handler
Browse files Browse the repository at this point in the history
  • Loading branch information
alex96jvm committed Aug 29, 2024
1 parent 77d741e commit 451b6f9
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,13 @@
import dev.alex96jvm.selmag.manager.service.ProductService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Locale;
import java.util.NoSuchElementException;

@Controller
Expand All @@ -20,10 +22,12 @@ public class ProductController {

private final ProductService productService;

private final MessageSource messageSource;

@ModelAttribute("product")
public Product product(@PathVariable("productId") int productId){
return this.productService.findProduct(productId)
.orElseThrow(() -> new NoSuchElementException("Товар не найден"));
.orElseThrow(() -> new NoSuchElementException("catalogue.errors.product.not_found"));
}

@GetMapping()
Expand Down Expand Up @@ -51,9 +55,11 @@ public String deleteProduct(@ModelAttribute("product") Product product){

@ExceptionHandler(NoSuchElementException.class)
public String noSuchElementException(NoSuchElementException e, Model model,
HttpServletResponse response){
HttpServletResponse response, Locale locale){
response.setStatus(HttpStatus.NOT_FOUND.value());
model.addAttribute("error", e.getMessage());
model.addAttribute("error",
this.messageSource.getMessage(e.getMessage(), new Object[0],
e.getMessage(), locale));
return "errors/404";
}

Expand Down
1 change: 0 additions & 1 deletion src/main/resources/application.properties

This file was deleted.

3 changes: 3 additions & 0 deletions src/main/resources/messages.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
catalogue.errors.product.not_found=Товар не найден
errors.404.title=Ничего не нашлось в магазине
errors.404.header=Ошибка 404: ничего не нашлось
4 changes: 2 additions & 2 deletions src/main/resources/templates/errors/404.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ничего не нашлось в магазине</title>
<title data-th-text="#{'errors.404.title'}"></title>
</head>
<body>
<h1>Ошибка 404: ничего не нашлось</h1>
<h1 data-th-text="#{'errors.404.header'}"></h1>
<h2 data-th-text="${error}"></h2>
</body>
</html>

0 comments on commit 451b6f9

Please sign in to comment.