How i can show error in the UI if i cant delete element from the Database

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

How i can show error in the UI if i cant delete element from the Database

lubo
Hi

I have this   controller that for deletion

    @GetMapping("/category/{categoryId}/delete")
    public String deleteCategory(@PathVariable Long categoryId) {
        categoryService.deleteById(categoryId);
        return "redirect:" + CATEGORY_NEW_URL + "";
    }

This si the HTML that has the delete button

 
                       <div class="panel-body">
                <table class="table table-hover ">
                    <thead class="thead-inverse">
                    <tr>
                        <th class="text-center">ID</th>
                        <th class="text-center">Description</th>
                        <th class="text-center">Edit</th>
                        <th class="text-center">Delete</th>
                    </tr>
                    <tr th:each="cat: ${categories}">
                        <td class="text-center" th:text="${cat.getId()}">334</td>
                        <td class="text-center" th:text="${cat.categoryName}">Article</td>
                        <td class="text-center"><a href="#" th:href="@{'/category/' + ${cat.getId()}}">
                            <span style="font-size:16px;color:orange" class="glyphicon glyphicon-edit"></span>
                        </a>
                        </td>
                        <td class="text-center"><a href="#" th:href="@{'/category/' + ${cat.getId()} + '/delete'}">
                            <span style="font-size:16px ;color:red" class="glyphicon glyphicon-trash"></span></a>
                        </td>
                    </tr>
                </table>
            </div>




When I try to delete entity that have  coneciton to it I get this error

Caused by: java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`documentor`.`sub_categories`, CONSTRAINT `FK_sub_pages_pages` FOREIGN KEY (`primary_category_id`) REFERENCES `category` (`id`))

Caused by: java.sql.SQLIntegrityConstraintViolationException: Cannot delete or update a parent row: a foreign key constraint fails (`documentor`.`sub_categories`, CONSTRAINT `FK_sub_pages_pages` FOREIGN KEY (`primary_category_id`) REFERENCES `category` (`id`))

How i can hande  this to show mesage that this element cant be dleted

I add validation in the other places like this


    @PostMapping("/category/{categoryId}")
    public String updateCategory(@Valid Category category, BindingResult result, RedirectAttributes re) {
        if (result.hasErrors()) {
            re.addFlashAttribute("org.springframework.validation.BindingResult.category", result);
            re.addFlashAttribute("category", category);
            return "redirect:/category/" + category.getId() + "";
        }
        categoryService.saveCategory(category);
        return "redirect:" + CATEGORY_NEW_URL + "";
    }


    @RequestMapping(value = CATEGORY_NEW_URL, method = RequestMethod.GET)
    public String newCategory(Model model) {
        Category category = new Category();
        if (!model.containsAttribute("category")) {
            model.addAttribute("category", category);
            model.addAttribute("categories", categoryService.getAllCategories());
        }
        return "category/category";
    }


                        <div class="panel-body">
                            <div class="row">
                                <div class="col-md-9 form-group" th:class="${#fields.hasErrors('categoryName')}
                                ? 'col-md-9  form-group has-error' : 'col-md-9  form-group'">
                                    <label>Category Name:</label>
                                    <label>
                                        <input type="text" class="form-control" th:field="*{categoryName}"/>
                                    </label>
                                   
                                        <ul>
                                            <li th:each="err : ${#fields.errors('categoryName')}" th:text="${err}"></li>
                                        </ul>
                                   

                                </div>
                            </div>
                        </div>
Reply | Threaded
Open this post in threaded view
|

Re: How i can show error in the UI if i cant delete element from the Database

Avec
This post was updated on .
There is several ways for you to handle errors. Here are some.

You can implement ErrorController and create your own handling. Take a look at how you can do this in this simple error-handling project I made a few days ago.

I however went for a simpler and better way to handle errors in my mind.

Spring comes with its own implementation of ErrorController named BasicErrorController. This class handles both HTML and JSON handeling. It is easy to display the error values. Take a look at another one of my projects where I show what values you can display. Place an error.html in /resources/templates.
If you clone this project and start the server then access http://localhost:8081/non_existing_url you will be redirected to the error page.

If you want to display the error back to the same page (template) you should return two alternatives. I assume  "redirect:" + CATEGORY_NEW_URL + ""; is the same page where delete was initiated.
@GetMapping("/category/{categoryId}/delete")
public String deleteCategory(@PathVariable Long categoryId, Model model) {
    try {
        categoryService.deleteById(categoryId);
        return "redirect:" + CATEGORY_NEW_URL + "";
    } catch (Exception e) {
        String errorMsg ="whatever";
        model.addAttribute("errorMsg", errorMsg); // display this if it is there
        return "redirect:" + CATEGORY_NEW_URL + "";
    }
}

I am sure you will find something that will work for you. Good luck.
Reply | Threaded
Open this post in threaded view
|

Re: How i can show error in the UI if i cant delete element from the Database

lubo
Hi thanks for the help will check it.
I'm new in this and a lot of the stuff i found are very complicated for me.

I found a way to do handle it but I'm sure it's not the correct way.

    @Override
    public Integer getSubCategoryCount(Long categoryId) {
        return subCategoryRepository.countByPrimaryCategoryId(categoryId);
    }

    @Override
    public Boolean checkIfCategoryCanBeDeleted(@PathVariable("categoryId") Long categoryId) {
        return subCategoryService.getSubCategoryCount(categoryId) == 0;
    }
    @GetMapping("/category/{categoryId}/delete")
    public String deleteCategory(@Valid Category category, BindingResult result, RedirectAttributes re
            , @PathVariable Long categoryId) {
        var cat = categoryService.getCategoryById(categoryId).orElseThrow();
        if (!categoryService.checkIfCategoryCanBeDeleted(categoryId)) {
            re.addFlashAttribute("org.springframework.validation.BindingResult.delCat", result);
            re.addFlashAttribute("delCat", category);
            re.addFlashAttribute("category", category);
            re.addFlashAttribute("categories", categoryService.getAllCategories());
            return "redirect:" + CATEGORY_NEW_URL + "";
        }
        categoryService.deleteById(cat.getId());
        return "redirect:" + CATEGORY_NEW_URL + "";
    }

    <div class="col-md-3 col-md-offset-5">
        <div class="panel panel-primary">
            <div class="panel-heading">
                <h1 class="panel-title">Articles</h1>
            </div>
            <div class="panel-body" th:object="${delCat} ">
                <table class="table table-hover ">
                    <thead class="thead-inverse">
                    <tr>
                        <th class="text-center">ID</th>
                        <th class="text-center">Description</th>
                        <th class="text-center">Edit</th>
                        <th class="text-center">Delete</th>
                    </tr>
                    <tr  th:each="cat: ${categories}" >
                        <td class="text-center" th:text="${cat.getId()}">334</td>
                        <td class="text-center" th:text="${cat.categoryName}">Article</td>
                        <td class="text-center"><a href="#" th:href="@{'/category/' + ${cat.getId()}}">
                            <span style="font-size:16px;color:orange" class="glyphicon glyphicon-edit"></span>
                        </a>
                        </td>
                        <td class="text-center">
                            <a href="#" th:href="@{'/category/' + ${cat.getId()} + '/delete'}">
                            <span style="font-size:16px ;color:red" class="glyphicon glyphicon-trash"></span></a>
                       </td>
                    </tr>
                       <div  class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
                        <p  style="text-align: center">Cant delete Category with sub Category</p>
                    </div>
                </table>
            </div>
        </div>
    </div>




If you want i can show you the project