簡體   English   中英

如何實現錯誤頁面 Spring 引導

[英]How to implement an Error page Spring boot

如果客戶嘗試購買沒有庫存的產品,我正在嘗試制作具有錯誤頁面的 spring 應用程序。 我收到一條錯誤消息,提示HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException 每當我嘗試對此進行測試時, HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException 我嘗試了很多方法,我覺得我很接近。

請參閱下面的 controller,錯誤 class 只有 getter 和 setter 等

任何幫助將非常感激!!!

package com.sales.controllers;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.taglibs.standard.lang.jstl.LessThanOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.sales.exceptions.ErrorController;
import com.sales.models.Customer;
import com.sales.models.Order;
import com.sales.models.Product;
import com.sales.services.CustomerService;
import com.sales.services.OrderService;
import com.sales.services.ProductService;

@Controller                             //implementing the error class here
public class OrderController implements org.springframework.boot.autoconfigure.web.ErrorController {

    @Autowired
    ProductService ps;

    @Autowired
    CustomerService cs;

    @Autowired
    OrderService os;

    private Product prod;
    private Customer cust;

    ErrorController ec;



    @RequestMapping(value = "/showOrders.html")
    public String listOrders(Model model) {

        ArrayList<Order> orders = os.findAll();
        model.addAttribute("allOrders", orders);

        ArrayList<Customer> cust = cs.findAll();
        model.addAttribute("ordrs", cust);
        return "allOrders";
    }

    @RequestMapping(value = "/newOrder.html", method = RequestMethod.GET)
    public String addPerson(Model model) {
        ArrayList<Customer> customer = cs.findAll();
        ArrayList<Product> product = ps.findAll();

        Map<Long, String> customers = new LinkedHashMap<Long, String>();
        for (Customer c : customer) {
            customers.put(c.getcId(), c.getcName());

            model.addAttribute("customers", customers);

            Map<Long, String> products = new LinkedHashMap<Long, String>();
            for (Product p : product) {
                products.put(p.getpId(), p.getpDesc());

                model.addAttribute("products", products);
            }

        }
        Order o = new Order();

        model.addAttribute("orderList", o);

        return "addOrder";

    }

    @RequestMapping(value = "/newOrder.html", method = RequestMethod.POST)
    public String addOrderPost(@Valid @ModelAttribute("orderList") Order o, BindingResult result) {

        boolean qty = false;

        System.out.println("In order add");

        if (result.hasErrors()) {
            return "addOrder";
        }

        prod = ps.findOne(o.getProd().getpId());
        cust = cs.findOne(o.getCust().getcId());

        o.setProd(prod);
        prod.setQtyInStock(prod.getQtyInStock() - (o.getQty()));

        //if this happens the user should be redireccted with the following headings and error
        if (prod.getQtyInStock() < (o.getQty())) {
            ec.setHeader("Error creating the following order");
            ec.setError("Quantity to large: " + "Product stock" + prod.getQtyInStock());

            return "redirect:errorPage";
        }

        os.save(o);

        return "redirect:showOrders.html";

    }

    // Object that holds info related to the errors

        private static final String PATH = "/error";

        // adds ec object to the model and user is moved to the errorPage and error is
        // displayed
        @RequestMapping(value = PATH)
        public String errorPage(Model model) {

            System.out.println(ec.getHeader());
            System.out.println(ec.getError());

            model.addAttribute("exception", ec);

            return "errorPage";
        }
        @Override
        public String getErrorPath() {
            return PATH;
        }

}

錯誤頁面 (JSP)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <h1>${exception.header}</h1>
  <h2>${exception.error}</h2>
</body>
</html>


您需要處理您的異常類型的異常處理程序或處理任何類型異常的異常處理程序。

我個人更喜歡全局應用程序異常處理程序。 它們是在 @ControllerAdvice 注釋的幫助下創建的:

@ControllerAdvice
public class ResponseExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView handleAnyException(HttpServletRequest request, Exception e) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("your-error-page");

        return modelAndView;
    }
}

此異常處理程序將處理應用程序中的任何類型的異常,因為它處理 -> @ExceptionHandler(Exception.class) -> Exception.class。

如果您需要處理特定異常並提供與您需要將特定異常 class 放在 @ControllerAdvice 中不同的頁面。

例子:

    @ExceptionHandler(CustomException.class)
    public ModelAndView handleAnyException(HttpServletRequest request, CustomException e) {

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("your-custom-page");

        return modelAndView;
    }

關於異常處理的好文章: https://www.baeldung.com/exception-handling-for-rest-with-spring

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM