处理方式一:实现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> <h1>error-系统出错,请联系后台管理员</h1> </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>
<h1>500-系统错误</h1>
<h1>${roncooException}</h1>
</body>
</html>测试:输入一个会抛异常的URL
本文出自 “我爱大金子” 博客,请务必保留此出处http://1754966750.blog.51cto.com/7455444/1939359
原文地址:http://1754966750.blog.51cto.com/7455444/1939359