java - Spring boot如何实现Error页面
问题描述
如果客户尝试购买没有库存的产品,我正在尝试制作一个包含错误页面的 Spring 应用程序。HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException
每当我尝试对此进行测试时,我都会收到一条错误消息。我尝试了很多方法,我觉得我很接近。
请参阅下面的控制器,错误类只有 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。
如果您需要处理特定的异常并提供不同的页面,那么您需要将特定的异常类放在@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
推荐阅读
- r - 在每个值 x 轴的平均值上设置发散色标
- refresh - 制表器在数据刷新时突出显示条目
- docker - 如何将参数传递给特定于少数脚本而不是入口点的 docker run 命令
- hive - 在蜂巢中替代减号
- heroku - 在 Heroku 中使用 rclone mount?
- r - 结合两个金融数据集,交互式账户余额随时间变化
- python - 无法在 PyQt5 GUI 中的 QThread 中加载到 keras 模型
- python - boost/thread.hpp:没有这样的文件或目录
- django - Django:表单无效
- ios - 即使我没有使用任何 UIWebView,Apple 也不会接受我的应用程序