SpringBoot 默认的处理异常的机制: SpringBoot 默认的已经提供了一套处理异常的机制。 一旦程序中出现了异常 SpringBoot 会像/error 的 url 发送请求。在 springBoot 中提供了一个 叫 BasicExceptionController 来处理/error 请求,然后跳转到默认显示异常的页面来展示异常信息。
因此只需要在template目录下配置/error/404.html 和error/5xx.html即可,f发生异常会自动显示错误的页面。
如果想显示具体的错误,可以自定义异常:
//自定义异常,会将相关错误信息推送到前端页面 public class MyException extends RuntimeException{ private String message; public MyException(String message){ this.message =message; } public String getMessage(){ return this.message; } }错误页面:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h2>500! 对不起,页面出错了~</h2> <span>${message}</span> </body> </html>控制器异常:
@RequestMapping("/updatepass") public String updatepass(@RequestParam("id") Integer id, @RequestParam(value = "passwd",defaultValue = "0") String passwd, @RequestParam(value = "repasswd",defaultValue = "0") String repasswd) { //验证密码是否相等 if(!passwd.equals(repasswd)){ throw new MyException("密码错误!"); } userService.updatePass(id,passwd,repasswd);//调用模型数据 return "redirect:/user/userlist"; }