您好,登录后才能下订单哦!
处理方式一:实现ErrorController接口
原理:Spring Boot 将所有的错误默认映射到/error, 实现ErrorController接口
代码:
package com.example.demo.controller;
import org.springframework.boot.autoconfigure.web.ErrorController;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by ly on 2017/6/17.
*/
@Controller
@RequestMapping("error")
public class BaseErrorController implements ErrorController {
@Override
public String getErrorPath() {
return "error/error";
}
@RequestMapping
public String error() throws Exception {
return getErrorPath();
}
}error.ftl:
<!DOCTYPE html> <html> <head lang="en"> <title>Spring Boot Demo - FreeMarker</title> </head> <body> <h2>error-系统出错,请联系后台管理员</h2> </body> </html>

在浏览器中输入一个不存在的URL,效果如下:

---------------------------------------------分割线---------------------------------------------
处理方式二:添加自定义的错误页面
对于html静态页面:
在resources/public/error/ 下定义
如添加404页面:resources/public/error/404.html页面,中文注意页面编码
对于模板引擎页面:
在templates/error/下定义
如添加5xx页面:templates/error/5xx.ftl
注:templates/error/ 这个的优先级比较 resources/public/error/高

效果:此处输入不存在的URL,则访问我们的404.hmtl;如果抛出异常,则访问我们的5xx.ftl


---------------------------------------------分割线---------------------------------------------
处理方式三:使用注解@ControllerAdvice(全局异常处理)
ExcepitonHandler.java
package com.example.demo.handler;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
/**
* Created by ly on 2017/6/17.
*/
@ControllerAdvice
public class ExcepitonHandler {
/**
* 统一异常处理
*
* @param exception
* exception
* @return
*/
@ExceptionHandler({ RuntimeException.class })
@ResponseStatus(HttpStatus.OK)
public ModelAndView processException(RuntimeException exception) {
System.out.println("自定义异常处理-RuntimeException");
ModelAndView m = new ModelAndView();
m.addObject("roncooException", exception.getMessage());
m.setViewName("error/500");
return m;
}
/**
* 统一异常处理
*
* @param exception
* exception
* @return
*/
@ExceptionHandler({ Exception.class })
@ResponseStatus(HttpStatus.OK)
public ModelAndView processException(Exception exception) {
System.out.println("自定义异常处理-Exception");
ModelAndView m = new ModelAndView();
m.addObject("roncooException", exception.getMessage());
m.setViewName("error/500");
return m;
}
}500.ftl:
<!DOCTYPE html>
<html>
<head lang="en">
<title>Spring Boot Demo - FreeMarker</title>
</head>
<body>
<h2>500-系统错误</h2>
<h2>${roncooException}</h2>
</body>
</html>测试:输入一个会抛异常的URL

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。