我正在尝试创建一个 Spring Boot 应用程序。我创建了一个简单的演示方法来展示我的问题。
@RequestMapping(value = "/customers", method = RequestMethod.GET)
public List<Customer> getCustomers() {
int i=0;
if(i==0){
throw new RuntimeException("test exception");
}
return (List<Customer>) jdbcCustomerDAO.findAll();
}
这里我抛出一个RuntimeException
。我想将其重定向到 ErrorController
,从我希望它在/src/main/webapp 内打开 error.jsp
的位置。
@Controller
public class MyCustomErrorController implements ErrorController{
@Override
public String getErrorPath() {
return "/error";
}
@GetMapping("/error")
public ModelAndView handleError(Model model) {
model.addAttribute("message", "Oops Sorry !!!!");
return new ModelAndView("error");
}
}
Error.jsp 文件
${message}
我在页面上收到此错误:
This page isn’t working
localhost is currently unable to handle this request.
HTTP ERROR 500
如何将其重定向到我的错误页面?
最佳答案
为什么不使用 Spring 自己的错误功能来捕获异常?您可以使用名为 ControllerAdvice
的东西(记录为 here )。因此,根据您的情况,您可以执行类似于以下操作的操作:
@ControllerAdvice
public class MyCustomErrorController {
@ExceptionHandler(RuntimeException.class)
public ModelAndView handleError(RuntimeException exception) {
model.addAttribute("message", "Oops Sorry !!!!");
return new ModelAndView("error");
}
}
您可能可以改用这种类型的错误处理。如果某些内容未按预期工作,请告诉我。还可以在 Spring 自己的 blog 上找到一个小引用。 .
关于java - 如果出现任何类型的异常,重定向到错误 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51495243/